How to Remove Event Listener in JavaScript

Harshit Jindal Feb 02, 2024
How to Remove Event Listener in JavaScript

This tutorial teaches how to remove an event listener in JavaScript.

Use the removeEventListener() Method to Remove Event Listener in JavaScript

If we create an element and we don’t want it to perform its intended behavior when the user interacts with it, we have to remove the event listener from that element. We achieve this by using JavaScript’s inbuilt function removeEventListener(). This function removes the attached event listener from an element and stops its predefined action. We can disable a click on a button by removing the event listener attached to it.

The function accepts the following parameters:

  1. type: It a string specifying the type of user action for which we want to remove the event listener.
  2. listener: The event listener function that we want to remove from the said element.
  3. options: It is an optional parameter that helps specify the event listener’s characteristics. The following options can be set:
    • capture: It is a boolean variable telling that the event will go to the registered listener before moving to any target event in the DOM tree.
    • mozSystemGroup: A boolean variable that indicates the event listener will be added to the system group. It is available only for code running in XBL/ Firefox’s chrome.
  4. useCapture: It is a boolean variable that tells whether the event listener is a capturing listener. It is also an optional parameter.
var element_name = document.querySelector('#btn');
var count = 0;
var counter = function(event) {
  count++;
  // perform the intended function in case of occurence of event
  if (count == 2) {
    this.removeEventListener('click', myHandler);
  }
} element_name.addEventListener('click', counter);

In the above code, we add an event listener and specify the function to perform if the listener is triggered. If the user tries to trigger the same listener again, we remove the event listener by using the removeEventListener(). We achieve this by first selecting the element on which we want to add/remove the event listener. Then, we initialize a counter to maintain the count of the number of clicks. Finally, we declare the event handler to trigger and also increment the count. In case the user clicks twice, the removeEventListener() is triggered.

Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn