Skip to content

Instantly share code, notes, and snippets.

@garystorey
Created January 27, 2015 17:13
Show Gist options
  • Save garystorey/36fb6d4fd2b9a4020202 to your computer and use it in GitHub Desktop.
Save garystorey/36fb6d4fd2b9a4020202 to your computer and use it in GitHub Desktop.
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