Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Last active October 16, 2018 07:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gordonbrander/d7b3dc4a0c15f950bcf7e6a4b7000ac7 to your computer and use it in GitHub Desktop.
Save gordonbrander/d7b3dc4a0c15f950bcf7e6a4b7000ac7 to your computer and use it in GitHub Desktop.
addEventDelegate() - easy event delegation
// Copyright 2018 Gordon Brander
// Released under MIT License https://opensource.org/licenses/MIT
const closest = (el, selector) =>
el.closest ? el.closest(selector) : null;
/**
* Delegate event handling to a parent element.
* @arg {Element} el - the parent element that we will be delegating handling to.
* @arg {string} selector - CSS selector of elements that should receive events.
* @arg {string} event - name of event
* @arg {function} callback - event callback. Takes 2 arguments event, and matched target.
* @arg {Object} options - event options
* @return {function} to remove event handler
*/
export const addEventDelegate = (el, selector, event, callback, options) => {
const onEvent = event => {
const target = closest(event.target, selector);
if (target) {
callback(event, target);
}
}
el.addEventListener(event, onEvent, options);
return () => el.removeEventListener(event, onEvent, options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment