Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active April 14, 2018 19:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathansmith/81fe0f1ac26d0b3b8979e1a06c758e25 to your computer and use it in GitHub Desktop.
Save nathansmith/81fe0f1ac26d0b3b8979e1a06c758e25 to your computer and use it in GitHub Desktop.
Event delegation helper.
/*
// Used like so:
onEvent('click', '.foo', (el) => {
// Element that was clicked.
console.log(el)
})
*/
// Event delegation helper.
const onEvent = (event, selector, f) => {
// Add listener.
document.addEventListener(event, (e) => {
// Get element.
const el = e.target.closest(selector)
// Matches CSS selector?
if (el) {
/*
NOTE: Remove these, if you want
the event to continue bubbling.
*/
e.preventDefault()
e.stopPropagation()
// Fire callback.
f(el)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment