Function addEventListener

  • A utility function to add an event listener to a specified element.

    This function adds an event listener for the specified event type and returns a function that can be called to remove the event listener.

    Example

    const button = document.getElementById('myButton');
    const removeClickListener = addEventListener(button, 'click', (event) => {
    console.log('Button clicked!');
    });

    // To remove the event listener later
    removeClickListener();

    Type Parameters

    • Element extends TEventElement

    • Target extends keyof HTMLElementEventMap

    • Listener extends ((event) => void)

    Parameters

    • element: Element

      The target element to which the event listener will be attached.

    • target: Target

      The name of the event to listen for (e.g., 'click', 'scroll').

    • listener: Listener

      The callback function to execute when the event occurs.

    • Optional options: boolean | AddEventListenerOptions

      Optional parameters for the event listener.

    Returns (() => void)

      • (): void
      • Returns void