Skip to content

Instantly share code, notes, and snippets.

@maurisrx
Created Jan 27, 2021
Embed
What would you like to do?
<!DOCTYPE html>
<html>
<head>
<title>Event Listener - JavaScript</title>
</head>
<body>
<div class="static">Static</div>
<button class="add" onclick="return false;">Add</button>
<script type="text/javascript">
document.querySelector( '.add' ).addEventListener( 'click', addElement );
function addElement() {
var static = document.querySelector( '.static' );
var dynamic = document.createElement( 'div' );
dynamic.classList.add( 'dynamic' );
dynamic.innerText = 'Dynamic';
static.insertAdjacentElement( 'afterend', dynamic );
}
/**
* 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 ) );
}
}
} );
}
setDynamicListener( 'click', '.dynamic', function( e ) {
e.target.remove();
} );
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment