Home >Web Front-end >JS Tutorial >Why is my JavaScript removeEventListener() not working?
Javascript removeEventListener not working
In this code, an event listener is added to an element using the addEventListener() method:
area.addEventListener('click',function(event) ...,true);
Later, in another function, the event listener is attempted to be removed using the removeEventListener() method:
area.removeEventListener('click',function(event) ...,true);
However, the event listener is not removed. Why is this happening?
The problem:
The issue lies in the fact that the two anonymous functions passed as arguments to the addEventListener() and removeEventListener() methods are two different functions. When the event listener is added with the following code:
area.addEventListener('click',function(event) ...,true);
The runtime creates a new, unique anonymous function object and assigns it to the click event handler of the area element.
When the event listener is removed with the following code:
area.removeEventListener('click',function(event) ...,true);
A different new, unique anonymous function object is created and assigned to the click event handler of the area element. The first function is not removed, so it continues to handle the click event.
Solution:
To correctly remove the event listener, it is necessary to provide the removeEventListener() method with a reference to the same function object that was passed to the addEventListener() method. To do this, the event listener should be defined as a named function, and then the named function should be used as an argument to both the addEventListener() and removeEventListener() methods. For example:
function foo(event) { app.addSpot(event.clientX,event.clientY); app.addFlag = 1; } area.addEventListener('click',foo,true); area.removeEventListener('click',foo,true);
The above is the detailed content of Why is my JavaScript removeEventListener() not working?. For more information, please follow other related articles on the PHP Chinese website!