Created
June 12, 2018 18:01
-
-
Save jsphkhan/1cbfc726bbedde8ff4576af79255d374 to your computer and use it in GitHub Desktop.
Event Delegation with Plain Vanilla JavaScript
This file contains 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
/* 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