Skip to content

Instantly share code, notes, and snippets.

@askehansen
Last active December 7, 2016 10:16
Show Gist options
  • Save askehansen/99a538d3b7909a3c48efb032a0bc1a6b to your computer and use it in GitHub Desktop.
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
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)
}
})
}
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