Junior
How to remove an event listener?
sobes.tech AI
Answer from AI
The removeEventListener() method is used to remove an event handler. This method takes the same three arguments as addEventListener():
- The event type (a string, e.g.,
'click','mouseover'). - A reference to the handler function that was assigned.
- An optional object or boolean value indicating the phase (capture or bubbling). It must match what was used when adding.
Important: To successfully remove an event listener, you must pass the exact same function reference that was used when adding. Anonymous functions created "on the fly" cannot be removed this way.
Example:
// Get the element
const element = document.getElementById('myButton');
// Define the handler function
function handleClick() {
console.log('Button clicked!');
}
// Add the handler
element.addEventListener('click', handleClick);
// ...some code...
// Remove the handler
element.removeEventListener('click', handleClick);
If the handler was added with options, for example useCapture: true, then they must also be specified when removing:
element.addEventListener('click', handleClick, { capture: true });
// ...
element.removeEventListener('click', handleClick, { capture: true });
If the third argument was omitted during addition (default value false), it can also be omitted or set to false during removal:
element.addEventListener('click', handleClick); // useCapture: false by default
// ...
element.removeEventListener('click', handleClick);
element.removeEventListener('click', handleClick, false); // equivalent to the above