If you have attached an event handler using the addEventListener()
method and want to remove that event handler, then call the removeEventListener()
method and pass a reference of that event handler to the removeEventHandler() method.
htmlElement.removeEventHandler(event, eventHandler);
Let's understand the entire process of removing an event handler with the help of an example:
Suppose there is a button and you have registered an event handler that will be called when a button is clicked.
<button id="btn">Click Me</button>
let btn = document.getElementById('btn'); function eventHandler(event){ alert('button is clicked'); } btn.addEventListener('click', eventHandler);
If you want to remove the event listener on the click event, then call the removeEventListener()
method and pass that event handler to it.
btn.removeEventListener('click', eventHandler);
Note: If the event handler is an anonymous function, then you won't be able to remove that event handler. This is because you don't have reference to that anonymous function.