Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Set event listener on dynamic elements
*
* {@link https://www.yudhistiramauris.com/how-to-add-javascript-event-listener-on-dynamic-elements/}
*
* @param {string} type Event name
* @param {string} selector CSS/JS selector
* @param {Function} callback Function to execute upon event trigger
*/
function setDynamicListener( type, selector, callback ) {
document.addEventListener( type, function( e ) {
if ( e.target.matches( selector ) ) {
var elements = this.querySelectorAll( selector );
for ( var i = 0; i < elements.length; i++ ) {
elements[i].addEventListener( type, callback( e ) );
}
}
} );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment