Remove an Event Handler

To remove an event handler previously registered using the addEventListener() method, you use the removeEventListener() method as follows:

element.removeEventListener(type, handler);Code language: CSS (css)

Suppose that you have a button with the class .btn:

<button class="btn">Register</button>Code language: HTML, XML (xml)

The following defines the click event handler:

function clickHandler(e) {
   console.log('Button Clicked');
}Code language: JavaScript (javascript)

The following add an event handler to the click event of the button:

const btn = document.querySelector('.btn');
btn.addEventListener('click', clickHandler);Code language: JavaScript (javascript)

To remove the click event handler from the click event of the button, you use the removeEventListener() method as follows:

btn.removeEventListener('click', clickHandler);Code language: JavaScript (javascript)

Note that the event and event handler must be the same. If you use an anonymous function as an event handler, you won’t be able to remove it. The following code doesn’t work:

const btn = document.querySelector('.btn');
// add an event listner
btn.addEventListener('click', function(e){
   console.log('Button Clicked');
});
// this code won't work and has no effect
btn.removeEventListener('click', function() {
   console.log('Button Clicked');
});Code language: JavaScript (javascript)

Most modern web browsers including Chrome, Firefox, and Edge support the removeEventListener() method.

IE8 doesn’t support the removeEventListener() method. It uses the detachEvent() method instead.

If you still need to support IE8, you can use the following helper function that works across browsers:

function removeEvent(el, type, handler) {
  if (el.detachEvent) {
    el.detachEvent('on' + type, handler);
  } else {
    el.removeEventListener(type, handler);
  }
}Code language: JavaScript (javascript)

Was this tutorial helpful ?