Created
January 27, 2015 17:13
-
-
Save garystorey/36fb6d4fd2b9a4020202 to your computer and use it in GitHub Desktop.
Event delegation in straight JS from http://bdadam.com/blog/plain-javascript-event-delegation.html
This file contains hidden or 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
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