Store the handler in a variable (not anonymous) and call removeEventListener with the same event type and the same function reference. Anonymous closures cannot be removed because you do not have a reference.
Callbacks and Event Listeners as Closures in JavaScript
How do you remove an event listener that is a closure in JavaScript?
The answer
More FAQs in Callbacks and Event Listeners as Closures in JavaScript
Yes. Every event listener closes over variables from where it was defined. This is how a click handler can access and update a count variable defined in the enclosing function.
Every callback is a closure. The callback function closes over variables from its defining scope. This is how setTimeout callbacks, map callbacks, and event handlers can access outer state when they run later.
Yes. If a listener closes over a DOM element and the element is removed from the DOM without removing the listener, the element stays in memory because the closure keeps a reference to it.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.