Last active
May 11, 2018 16:24
-
-
Save 0xch4z/9afc7d12bf37d13d174a19def0c95220 to your computer and use it in GitHub Desktop.
JQuery like event delegation for vanilla JS.
This file contains hidden or 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
| /** | |
| * helper function for event delegation | |
| * | |
| * @param {string} event - event name | |
| * @param {string} selector - selector for element | |
| * @param {(Event) => void} callback - callback to invoke with click event | |
| */ | |
| const addDynamicEventListener = (event, selector, handler) => { | |
| const _handler = function (e) { | |
| let target = e.target; | |
| while (target && target !== this) { | |
| if (target.matches(selector)) { | |
| handler.call(target, e); | |
| break; | |
| } | |
| target = target.parentElement; | |
| } | |
| }; | |
| document.body.addEventListener(event, _handler); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment