Skip to content

Instantly share code, notes, and snippets.

@jsphkhan
Created June 12, 2018 18:01
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 jsphkhan/1cbfc726bbedde8ff4576af79255d374 to your computer and use it in GitHub Desktop.
Save jsphkhan/1cbfc726bbedde8ff4576af79255d374 to your computer and use it in GitHub Desktop.
Event Delegation with Plain Vanilla JavaScript
/* Imagine we have a <div id="myDiv"></div> element. Suppose a new element <div class='new-element'></div> is appended
to the parent. Write a JS function that can do event delegation to an element that will be added in future. */
var parentRef = document.getElementById('myDiv'); //document.querySelector('#myDiv')
function delegate(type, elRef, callback) {
parentRef.addEventListener(type, function(evt) {
document.querySelectorAll(elRef).forEach(function(el) {
if(el === evt.target) {
callback.call(null, evt);
}
})
}, false);
}
delegate('click', '.new-element', function(evt) {
console.log('child element clicked', evt);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment