Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript removeEventListener not working

I have the following code to add eventListener

 area.addEventListener('click',function(event) {               app.addSpot(event.clientX,event.clientY);               app.addFlag = 1;           },true); 

It is working correctly as expected..Later in another function i tried to remove the event listener using the following code

 area.removeEventListener('click',function(event) {               app.addSpot(event.clientX,event.clientY);               app.addFlag = 1;           },true); 

But the even listener is not removed..Why is it happening?Is there any problem with my removeEventListener()? Note:Here area is something like document.getElementById('myId')

like image 248
Jinu Joseph Daniel Avatar asked May 04 '12 06:05

Jinu Joseph Daniel


People also ask

Why is my event listener not working?

If your event listener not working is dependent on some logic, whether it's about which element it'll listen on or if it's registered at all, the first step is to check that the listener is indeed added to the element. Using a breakpoint in the developer tools , a logpoint or console.

How do I remove all event listeners?

To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.

Can I use getEventListeners?

getEventListeners(obj) is only a Google Chrome specific Command Line Tool feature. This means that you can only use this feature inside Chrome Dev Tools when manually typing into the console. You cannot use this method in your actual JavaScript source code.


2 Answers

This is because that two anonymous functions are completely different functions. Your removeEventListener's argument is not a reference to the function object that was previously attached.

function foo(event) {               app.addSpot(event.clientX,event.clientY);               app.addFlag = 1;           }  area.addEventListener('click',foo,true);  area.removeEventListener('click',foo,true); 
like image 177
duri Avatar answered Oct 06 '22 00:10

duri


I find that for the windows object, the last param "true" is required. The remove doesn't work if there is no capture flag.

like image 37
Slavik Avatar answered Oct 06 '22 00:10

Slavik