How to check whether dynamically attached event listener exists or not with JavaScript?

Sometimes, we want to check whether dynamically attached event listener exists or not with JavaScript.

In this article, we’ll look at how to check whether dynamically attached event listener exists or not with JavaScript.

How to check whether dynamically attached event listener exists or not with JavaScript?

To check whether dynamically attached event listener exists or not with JavaScript, we can get and set the element’s listener attribute.

For instance, we write

export const attachEvent = (
  element: Element,
  eventName: string,
  callback: () => void
) => {
  if (element && eventName && element.getAttribute("listener") !== "true") {
    element.setAttribute("listener", "true");
    element.addEventListener(eventName, () => {
      callback();
    });
  }
};

to get the listener attribute with element.getAttribute("listener").

If it’s set to 'true', then the listener is attached.

Otherwise, we attach it with addEventListener and call setAttribute to set the listener attribute to true.

Then we use it like

attachEvent(domElement, "click", listenerFunc)

by calling it with the element, event name, and event handler function.

Conclusion

To check whether dynamically attached event listener exists or not with JavaScript, we can get and set the element’s listener attribute.