Skip to content

Commit

Permalink
feat: Add dom.addDelegatedListener
Browse files Browse the repository at this point in the history
  • Loading branch information
uxder committed Nov 2, 2021
1 parent ca781f4 commit 202775a
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/dom/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1217,10 +1217,63 @@ export function removeNativeLazyImage(rootElement: HTMLElement) {
});
}

/**
* Listens for a specified event on any element within the provided element and
* then recursively calls the listener on all ancestors of the originating
* element.
*
* For example a given module, when any click event happens within the module,
* call your listener repeatedly starting from the originating element and all
* of its ancestors (bubble up) up to the document root.
*
* ```ts
* dom.addDelegatedListener(
* myModuleElement || document.documentElement,
* 'click',
* (e: HTMLElement, event: any) => {
* if (!e) {
* return;
* }
* // Called on the element that was clicked and it's parent
* // recursively until the document root.
* ...
* }
* );
* ```
*
* @param {Element} el Element to host the listener.
* @param {string} type Listener type.
* @param {function} listener Listener function.
*/
export function addDelegatedListener(
el: HTMLElement,
type: string,
listener: Function
) {
const handler = (e: any) => {
e = e || window.event;
let target = e.target || e.srcElement;
target = target.nodeType === 3 ? target.parentNode : target;
do {
listener(target, e);
if (target.parentNode) {
target = target.parentNode;
}
} while (target.parentNode);
};
el.addEventListener(type, handler);

// Return a function to remove the listener.
return () => {
el.removeEventListener(type, handler);
};
}

/**
* Degu DOM utility functions.
*/
export const dom = {
addDelegatedListener,
addStyles,
addStylesToPage,
appendAfter,
Expand Down

0 comments on commit 202775a

Please sign in to comment.