Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an anonymous event listener

Is there anyway to remove an event listener added like this:

element.addEventListener(event, function(){/* do work here */}, false); 

Without replacing the element?

like image 263
erikvold Avatar asked Jun 24 '10 01:06

erikvold


People also ask

Can you remove event listener with anonymous function?

To call removeEventListener with an anonymous function with JavaScript, we assign the anonymous event listener function to a variable and call addEventListener and removeEventListener with the variable.

How do I remove an event listener from my website?

Event listeners can also be removed by passing an AbortSignal to an addEventListener() and then later calling abort() on the controller owning the signal.

Should you remove event listeners?

TLDR; Always remove event listeners when you don't plan on using them any longer.


2 Answers

There is no way to cleanly remove an event handler unless you stored a reference to the event handler at creation.

I will generally add these to the main object on that page, then you can iterate and cleanly dispose of them when done with that object.

like image 200
Joe Avatar answered Sep 21 '22 04:09

Joe


You could remove the event listener like this:

element.addEventListener("click", function clicked() {     element.removeEventListener("click", clicked, false); }, false); 
like image 22
icktoofay Avatar answered Sep 24 '22 04:09

icktoofay