JavaScript Reference ยท DOM: Events
EventTarget.removeEventListener() method
Reference for removeEventListener(): detach an event handler, match the same function and capture flag, and use once or AbortController as easier alternatives.
The removeEventListener() method detaches a listener that was added earlier with addEventListener(). After it is removed, the function is no longer called when the event fires.
The browser looks for a registration that matches on three things: the event type, the listener function, and the capture flag. All three must be equal to what you used when adding it. If nothing matches, the call quietly does nothing.
target.removeEventListener(type, listener); target.removeEventListener(type, listener, options);
Try it
Syntax
removeEventListener(type, listener) removeEventListener(type, listener, options) removeEventListener(type, listener, useCapture)
Parameters
| Name | Description |
|---|---|
type |
The event name used when the listener was added, for example "click". |
listener |
The exact function (or handleEvent object) that was registered. |
options |
Optional object. Only capture matters here; other properties such as once and passive are ignored. |
useCapture |
Optional boolean, the older form of { capture }. Defaults to false. |
Return value
undefined.
Usage notes
- Same reference required.
el.removeEventListener("click", () => {})never removes anything, because the new arrow function is a different object. Store the function in a variable or use a named function. - Match the capture flag. A listener added with
{ capture: true }is removed only by a call withcapture: true. A mismatch is a frequent reason why "removeEventListener does not work". - Bound functions are new functions.
fn.bind(this)returns a new function each time. Save the bound result once and use that same reference for both add and remove. - Safe to call when nothing matches. It never throws for an unknown listener, so you can call it defensively during cleanup.
- Removing inside the listener. A listener may remove itself while it runs. The current call finishes normally.
- Easier alternatives. The
once: trueoption removes the listener after its first call, and asignalfrom anAbortControllerremoves any number of listeners with oneabort(). - Memory. Listeners keep their closures alive. Remove them when you delete long-lived targets such as
windowordocumentlisteners from a component that goes away.
Browser support
removeEventListener() works in every browser. Passing an options object as the third argument is also widely supported; check a compatibility table if you need very old browsers.
Related
EventTarget.addEventListener()โ register a listener- the
onceandsignaloptions โ self-removing listeners - event bubbling and capturing โ what the capture flag means
- Lesson: Events