Skip to content

Instantly share code, notes, and snippets.

@ronen-e
Created May 30, 2016 13:12
Show Gist options
  • Select an option

  • Save ronen-e/74d2ccc4ffdf27b3f6b52a38c8ce96f4 to your computer and use it in GitHub Desktop.

Select an option

Save ronen-e/74d2ccc4ffdf27b3f6b52a38c8ce96f4 to your computer and use it in GitHub Desktop.
function delegate(element, eventName, selector, handler) {
var el = null;
element.addEventListener(eventName, function delegatedListener(e) {
el = e.target;
while (el !== element && el.parentNode) {
if (el.nodeType === 1 && selectorMatches(el, selector)) {
handler(e, el);
break;
}
el = el.parentNode;
}
}, false);
}
function selectorMatches(el, selector) {
var p = Element.prototype;
var f = p.matches || p.webkitMatchesSelector || p.mozMatchesSelector || p.msMatchesSelector || function(s) {
return [].indexOf.call(document.querySelectorAll(s), this) !== -1;
};
return f.call(el, selector);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment