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.

    Type Parameters

    • Target extends keyof HTMLElementEventMap
    • Listener extends (event: DocumentEventMap[Target]) => void

    Parameters

    • element: Document | Element | Window

      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.

    • Optionaloptions: boolean | AddEventListenerOptions

      Optional parameters for the event listener.

    Returns () => void

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

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