Menü schliessen
Created: March 3rd 2023
Last updated: March 24th 2023
Categories: Common Web Development,  JavaScript Development
Author: Tim Fürer

JavaScript: Live event listener

Tags:  function,  Javascript,  web
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

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).


Implementation

/**
 * 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.


Example

// listen for clicks on elements with the class .myButton

addLiveListener('click', '.myButton', (target, event) => {
  // do something
});