Skip to content

Instantly share code, notes, and snippets.

@wiseoldman
Last active June 2, 2023 12:47
Show Gist options
  • Save wiseoldman/74432582f0b6880c918bdfbe8da250c6 to your computer and use it in GitHub Desktop.
Save wiseoldman/74432582f0b6880c918bdfbe8da250c6 to your computer and use it in GitHub Desktop.
[Event delegation] Vanilla js event delegation. This also works for complex HTML markup with overlaying children #event #delegation
Element.prototype.on = function (eventName, selector, fn) {
this.addEventListener(eventName, function (event) {
const target = event.target.closest(selector)
if (target && this.contains(target)) {
return fn.call(target, event, target)
}
})
}
document.querySelector('body').on('click', '.item', (e, el) => {
console.log(e);
console.log(el);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment