Created
October 27, 2016 17:59
-
-
Save mhairston/43937b7021db99c8459282eec8566299 to your computer and use it in GitHub Desktop.
Event Delegation with Plain 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
// 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