Skip to content

Instantly share code, notes, and snippets.

@liximomo
Last active December 17, 2016 09:33
Show Gist options
  • Save liximomo/4694bbb387908e18615ed145631d90dc to your computer and use it in GitHub Desktop.
Save liximomo/4694bbb387908e18615ed145631d90dc to your computer and use it in GitHub Desktop.
event delegate without javascript library ie9+
function on(elSelector, eventName, selector, handler, useCapture) {
const _useCapture = useCapture === undefined ? false : useCapture;
const elements = document.querySelectorAll(elSelector);
const addEventListener = function(element) {
element.addEventListener(eventName, function(e) {
for (let target = e.target; target && target != this; target = target.parentNode) {
// loop parent nodes from the target to the delegation node
let match = false;
if (target.matches) {
match = target.matches(selector);
} else if (target.webkitMatchesSelector) {
match = target.webkitMatchesSelector(selector);
} else if (target.mozMatchesSelector) {
match = target.mozMatchesSelector(selector);
} else if (target.msMatchesSelector) {
match = target.msMatchesSelector(selector);
} else if (target.oMatchesSelector) {
match = target.oMatchesSelector(selector);
}
if (match) {
handler.call(target, e);
break;
}
}
}, _useCapture);
};
Array.prototype.forEach.call(elements, addEventListener);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment