Created
January 27, 2021 12:51
-
-
Save maurisrx/c30aeb6800a220d70f83604f952ff97d to your computer and use it in GitHub Desktop.
JavaScript - Set event listener on dynamic elements: https://www.yudhistiramauris.com/how-to-add-javascript-event-listener-on-dynamic-elements/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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