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')
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.
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.
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.
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);
I find that for the windows object, the last param "true" is required. The remove doesn't work if there is no capture flag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With