How to Remove Event Listeners in JavaScript

Updated onbyAlan Morel
How to Remove Event Listeners in JavaScript

JavaScript makes it easy to add functionality to web pages by adding event listeners to elements.

Event listeners are functions that you can set to run when a specific event occurs on a specific element. For example, you can set a function to run when a user clicks a button.

When you no longer need an event listener, you can remove it. This is important because if you don’t remove an event listener, it will continue to run every time the event occurs, even if you no longer need it to.

In this post, we'll learn how to remove event listeners in JavaScript.

How to remove event listeners

First, let's look at how to add an event listener. We'll use the addEventListener() method to add an event listener to a button.

const button = document.querySelector("button");

const callback = () => {
  console.log("Button clicked");
};

button.addEventListener("click", callback);

When the user clicks the button, the callback() function will run.

Now that we've added an event listener, let's remove it. We'll use the removeEventListener() method to remove the event listener.

button.removeEventListener("click", callback);

When the user clicks the button, the callback() function will no longer run.

Notice that we need to pass in the same event type and callback function to the removeEventListener() method as we did to the addEventListener() method.

Without the event type and callback function, the removeEventListener() method won't know which event listener to remove.

This is why it is not recommended to pass in anonymous functions to the addEventListener() method, like this:

button.addEventListener("click", () => {
    console.log("Button clicked");
});

Conclusion

In this post, we learned how to remove event listeners in JavaScript.

Simply keep track of the event type and callback function you used to add the event listener, and pass them to the removeEventListener() method to remove the event listener.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.