Remove an anonymous event listener

Sun Oct 17 2021


In one of my interviewing processes the interviewer forwarded the following piece of code and asked me, "How do I remove this event listener?"

1document.getElementById("download").addEventListener("click", () => { 2 // perform download activities 3})

I hope the code block was enough time for you to answer the question - you can't remove an anonymous event listener and that is exactly what I answered.

If that is all I wanted to say this would be one of the shortest blogs I have written 😊

In one of our discussions with my colleague Alberto Delgado, we came across the concept of Abortable Event Listeners

The optional 3rd parameter

eventType and eventListener are the 2 most commonly used parameters of addEventListener, however, we can pass an additional 3rd parameter which could be an options object or useCpature: boolean (more on this in a future blog post).

The optional 3rd parameter is used in multiple case like

  1. if we want to fire an event only once {once: true/false}
  2. if we want to make a listener passive {passive: true/false}
  3. if we want to fire an event listener in capturing/bubbling phase {capture: true/false}

The signal option

Another value that we can add to this options object is signal which takes a signal object and we can use its reference to remove our event listener.

Inspect with Chrome Dev Tools

If we inspected our page using the Chrome Dev Tools, we can see that "Download Button" has a click event listener attached to it and when clicking it the listener is called and we can see the console.log message being printed.

Registered anonymous event listener

However, inspecting the "Download Button" after clicking the "Abort Button", the listener is no longer available.

Anonymous event listener removed

Removing multiple event listeners simultaneously

Now that we know this way of removing event listeners we can extend it to remove multiple event listeners simultaneously. Instead of keeping a track of the multiple events we want to remove and calling removeEventListener for each of them individually, we can sort of categorize them under 1 controller and abort that controller thereby removing all those event listeners.

1const downloadController = new AbortController(); 2 3const button = document.getElementById("download"); 4button.addEventListener('mouseover', () => { 5 // do mouse over things 6}, { signal: downloadController.signal }); 7 8button.addEventListener('click', () => { 9 // do click event things 10}, { signal: downloadController.signal }); 11 12const abortButton = document.getElementById("abort"); 13abortButton.addEventListener("click", () => { 14 // will remove all the event listeners 15 downloadController.abort(); 16}) 17
In conclusion

If your application needs to support IE11 this method will not work.