UNPKG

vanillajs-browser-helpers

Version:

Collection of convenience code snippets (helpers) that aims to make it a little easier to work with vanilla JS in the browser

51 lines (50 loc) 1.53 kB
import isEventTarget from './isEventTarget'; import on from './on'; import off from './off'; import matches from './matches'; /** * Creates a function that triggers the given handler if the current event target * matches the given selector * * @param selector - CSS Selector that matches the element to delegate the event to * @param handler - Handler to trigger if selector selector match * @return The delegate event handler * * @example * * ```ts * const handler = delegateHandler('.my-element', (e: Event) => {}); * document.addEventHandler('click', handler); * ``` */ export function delegateHandler(selector, handler) { const cb = 'handleEvent' in handler ? handler.handleEvent : handler; return (e) => { let target = e.target; while (target && !matches(target, selector)) { const parent = target.parentElement; if (!parent) { return; } target = parent; } const evt = e; evt.delegateTarget = target; return cb.call(target, evt); }; } function delegate(target, eventNames, selector, handler, options) { if (!isEventTarget(target)) { options = handler; handler = selector; selector = eventNames; eventNames = target; target = document; } const delHandler = delegateHandler(selector, handler); on(target, eventNames, delHandler, options); return () => off(target, eventNames, delHandler); } export default delegate;