Remove an Event Listener with JavaScript | Plantpot

Remove an Event Listener with JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to remove an event listener with JavaScript.

removeEventListener

Use the removeEventListener method to remove the event listener.

The syntax of removeEventListener is as follows.
As for the argument, option and useCapture can be specified as well as addEventListener.

target.removeEventListener(type, listener[, options]);
target.removeEventListener(type, listener[, useCapture]);

Below is a sample to delete the event listener after clicking the button.

HTML

<button id="btn">Click Me!</button>

JavaScript

let btn = document.getElementById('btn');
const onClick = ()=> {
  alert('Remove an event listener');
  btn.removeEventListener('click', onClick, false);
}

btn.addEventListener('click', onClick, false);