Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of removeEventListener

Please check the below code:

var clickfn = function(){
 alert("clicked");                    
}
document.getElementById("div1").addEventListener("click",clickfn,true);
clickfn = function(){  };
document.getElementById("div1").removeEventListener("click");

http://jsfiddle.net/qUtzL/4/

Why does the removeEventListener does not work?

like image 549
Gautham Renganathan Avatar asked Nov 20 '12 13:11

Gautham Renganathan


People also ask

How do I know if removeEventListener is working?

After your call to removeEventListener is made, go back and check your event listeners again. If it was successful, your event listener should no longer be set. Once you're done debugging, you can then resume code execution (F8).

Why do you need to remove event listeners?

If event listeners are not removed, it will cause memory leak for older browsers (IE 6 and 7, if i recall correctly). Hence will cause unnecessarily high memory utilization which will lead to many problems.

How can you remove an event listener and prevent the flashing bug?

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

Which of the following is used to remove the event listener?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.


1 Answers

removeEventListener takes 2 parameters, the event, and the function to remove.
This should work:

document.getElementById("div1").removeEventListener("click", clickfn);

Also, the function you're executing is empty.

var clickfn = function(){  };
like image 171
Cerbrus Avatar answered Oct 10 '22 00:10

Cerbrus