Skip to content

Instantly share code, notes, and snippets.

@maurisrx
Created January 27, 2021 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maurisrx/c30aeb6800a220d70f83604f952ff97d to your computer and use it in GitHub Desktop.
Save maurisrx/c30aeb6800a220d70f83604f952ff97d to your computer and use it in GitHub Desktop.
/**
* 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