Delegates events to a selector.
Parameters:
Name | Type | Description |
---|---|---|
elements | string | | A selector string, or element/array of elements. |
selector | string | the selector string to search for and delegate. |
type | string | | The event type or a function to execute. |
callback | function | The callback function to execute. |
useCapture | boolean | Whether to use useCapture or not. https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#usecapture |
- Since
- 1.0.0
- Source
Returns:
Destroy method is returned on instance.
- Type:
- Array.<unknown> |
Object | *
Example
import { delegate } from "@gravityforms/utils";
// With the default base (document)
delegate( '.btn', 'click', function( e ) {
console.log( e.delegateTarget );
}, false );
// With an element as base
delegate( document.body, '.btn', 'click', function( e ) {
console.log( e.delegateTarget );
}, false );
// With a selector (of existing elements) as base
delegate( '.container', '.btn', 'click', function( e ) {
console.log( e.delegateTarget );
}, false );
// With an array/array-like of elements as base
delegate( document.querySelectorAll( '.container' ), '.btn', 'click', function( e ) {
console.log( e.delegateTarget );
}, false );
// Remove delegation
// With a single base element (default or specified)
const delegation = delegate( document.body, '.btn', 'click', function( e ) {
console.log( e.delegateTarget );
}, false );
delegation.destroy();
// With multiple elements (via selector or array)
// Note: selectors are always treated as multiple elements, even if one or none are matched. delegate() will return an array.
const delegations = delegate( '.container', '.btn', 'click', function( e ) {
console.log( e.delegateTarget );
}, false );
delegations.forEach( function( delegation ) {
delegation.destroy();
} );