Skip to content

Instantly share code, notes, and snippets.

@0xch4z
Last active May 11, 2018 16:24
Show Gist options
  • Select an option

  • Save 0xch4z/9afc7d12bf37d13d174a19def0c95220 to your computer and use it in GitHub Desktop.

Select an option

Save 0xch4z/9afc7d12bf37d13d174a19def0c95220 to your computer and use it in GitHub Desktop.
JQuery like event delegation for vanilla JS.
/**
* 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