Could we help you? Please click the banners. We are young and desperately need the money
You might know of the concept of live listeners from jQuery, it being one of the libraries that popularised them. Live listeners allow developers to define event listeners that can be triggered by multiple elements as well as elements that are added to the DOM after the definition of the listener. They are able to do that, because they aren't bound to a target element, but a document selector instead (which makes them reliant on event bubbling).
/**
* Adds a live event listener to the document.
* @param {keyof DocumentEventMap} type The event type to listen for.
* @param {keyof HTMLElementTagNameMap} selector A string containing a valid CSS selector to match for the listener's target elements.
* @param {(Target: HTMLElement, event: Event) => {}} callback The function to call when the listened-to event occurs on a target.
*/
function addLiveListener(type, selector, callback) {
document.addEventListener(type, event => {
const Target = event?.target?.closest?.(selector);
if (!Target)
return;
callback(Target, event);
});
}
Use the first parameter "type" to define the type of event to listen for. The event must bubble all the way to the document root in order to be compatible with this technique. For example, the event "click" (under normal circumstances), would be suitable.
Use the second parameter "selector" to define what elements to listen for via a CSS selector string.
Use the third parameter "callback" to define the function to call when a listened-for element fired the listened-for event. This callback function will be provided as parameters with a reference to the element that fired the event and a reference to the fired event object.
// listen for clicks on elements with the class .myButton
addLiveListener('click', '.myButton', (target, event) => {
// do something
});