Delegates events to a selector.

Parameters:
NameTypeDescription
elementsstring | Array | NodeList | HTMLElement

A selector string, or element/array of elements.

selectorstring

the selector string to search for and delegate.

typestring | function

The event type or a function to execute.

callbackfunction

The callback function to execute.

useCaptureboolean

Whether to use useCapture or not. https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#usecapture

Since
  • 1.0.0
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();
} );