Home > Web Front-end > JS Tutorial > Why is my JavaScript removeEventListener() not working?

Why is my JavaScript removeEventListener() not working?

Susan Sarandon
Release: 2024-11-02 14:42:30
Original
690 people have browsed it

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);
Copy after login
Copy after login

Later, in another function, the event listener is attempted to be removed using the removeEventListener() method:

area.removeEventListener('click',function(event) ...,true);
Copy after login
Copy after login

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);
Copy after login
Copy after login

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);
Copy after login
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template