Last active
April 14, 2018 19:31
-
-
Save nathansmith/81fe0f1ac26d0b3b8979e1a06c758e25 to your computer and use it in GitHub Desktop.
Event delegation helper.
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
/* | |
// 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