Last active
December 17, 2016 09:33
-
-
Save liximomo/4694bbb387908e18615ed145631d90dc to your computer and use it in GitHub Desktop.
event delegate without javascript library ie9+
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
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