Last active
December 7, 2016 10:16
-
-
Save askehansen/99a538d3b7909a3c48efb032a0bc1a6b to your computer and use it in GitHub Desktop.
jQuery style event handler that attaches to the document so it works on dynamically added elements
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 (eventName, selector, callback) { | |
document.addEventListener(eventName, function (event) { | |
var elem = event.srcElement | |
var matches = elem.matches || elem.matchesSelector | |
if (matches.call(elem, selector)) { | |
callback.call(elem) | |
} | |
}) | |
} |
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
on('click', 'button.say-hello', function () { | |
alert('hello') | |
console.log(this) /* <button class="say-hello"></button>" */ | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment