Last active
June 2, 2023 12:47
-
-
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
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
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) | |
} | |
}) | |
} |
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
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