Skip to content

Instantly share code, notes, and snippets.

@mhairston
Created October 27, 2016 17:59
Show Gist options
  • Save mhairston/43937b7021db99c8459282eec8566299 to your computer and use it in GitHub Desktop.
Save mhairston/43937b7021db99c8459282eec8566299 to your computer and use it in GitHub Desktop.
Event Delegation with Plain JavaScript
// Event Delegation with Plain Javascript
// from Adam Beres-Deak
// http://bdadam.com/blog/plain-javascript-event-delegation.html
function on(elSelector, eventName, selector, fn) {
var element = document.querySelector(elSelector);
element.addEventListener(eventName, function(event) {
var possibleTargets = element.querySelectorAll(selector);
var target = event.target;
for (var i = 0, l = possibleTargets.length; i < l; i++) {
var el = target;
var p = possibleTargets[i];
while(el && el !== element) {
if (el === p) {
return fn.call(p, event);
}
el = el.parentNode;
}
}
});
}
on('#list', 'click', '.yes', function(e) {
// this function is only called, when a list item with 'yes' class is called
console.log(e.target); // this is the clicked list item
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment