Skip to content
jshacks.dev
Browser

How to Add and Remove Event Listeners Properly

Add and remove event listeners properly in JavaScript: matching references, the once and signal options, capture, passive, delegation and avoiding memory leaks.

9 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, GraphQL, NGINX and Swagger logos.

Event listeners are the way a page reacts to anything: clicks, keys, scrolling, network messages, timers in the form of custom events. Adding one takes a single line, and most of the bugs that come later are about the other half. A listener that was never removed keeps a component alive after it is gone, so memory climbs and handlers fire for things the user can no longer see. A call to removeEventListener() that silently does nothing leaves the handler in place, because the arguments did not match the ones used to add it. A handler added twice runs twice. This guide shows how to add and remove event listeners properly in JavaScript: the signature of both methods and the rule that makes removal work, the options that matter (once, signal, capture, passive), how to clean up with an AbortController, how event delegation reduces the number of listeners, how to avoid leaks in components, how to handle this and arguments, and how to test that cleanup happened. The methods belong to EventTarget in the DOM Standard, documented on MDN, and work in every browser, in workers and in Node.js, whose EventTarget follows the same interface.

The basic pair

addEventListener(type, listener, options) registers a function to be called when an event of that type reaches the target. removeEventListener(type, listener, options) unregisters it.

basic.jsJavaScript
const button = document.createElement("button");
document.body.append(button);

function onClick(event) {
  console.log("clicked", event.type);
}

button.addEventListener("click", onClick);
button.click();

button.removeEventListener("click", onClick);
button.click();
Text
clicked click

The second click printed nothing, because the listener was removed. The listener runs with the event object as its argument, and the return value is ignored. Returning false does not cancel anything here, unlike in old inline onclick attributes, so use event.preventDefault().

Removal needs the same reference

The most common mistake is trying to remove a function that is not the one that was added. Removal compares the event type, the listener function by identity, and the capture flag. An arrow function written inline is a new function each time, so there is nothing to match.

identity.jsJavaScript
const target = new EventTarget();

target.addEventListener("ping", () => console.log("ping 1"));
target.removeEventListener("ping", () => console.log("ping 1"));

target.dispatchEvent(new Event("ping"));
Text
ping 1

The two arrow functions look identical but are different objects, so the removal found nothing and the listener still fires. The fix is to keep a reference in a variable, or to use an option that does not require one, as the sections below show.

named.jsJavaScript
const target = new EventTarget();
const onPing = () => console.log("ping");

target.addEventListener("ping", onPing);
target.removeEventListener("ping", onPing);

target.dispatchEvent(new Event("ping"));
console.log("done");
Text
done

The same listener is added only once

Adding the same function with the same type and capture flag twice does not register it twice: the second call is ignored. That makes it safe to call setup code more than once with a named function, and it is also why an anonymous function, which is a new object each time, is registered every time and runs several times.

duplicate.jsJavaScript
const target = new EventTarget();
const named = () => console.log("named");

target.addEventListener("x", named);
target.addEventListener("x", named);
target.addEventListener("x", () => console.log("anonymous"));
target.addEventListener("x", () => console.log("anonymous"));

target.dispatchEvent(new Event("x"));
Text
named
anonymous
anonymous

If a function that adds a listener can be called repeatedly, such as a render function, define the handler once outside it, or remove before adding, otherwise the handlers pile up and each event triggers many calls.

The capture flag must match

A listener can be registered for the capture phase, which runs on the way down the tree, or the bubble phase, the default. A capture listener and a bubble listener with the same function are different registrations, and removing one does not remove the other. Pass the same capture value when you remove.

capture.jsJavaScript
const target = new EventTarget();
const handler = () => console.log("handler");

target.addEventListener("x", handler, true);
target.removeEventListener("x", handler);
target.dispatchEvent(new Event("x"));

target.removeEventListener("x", handler, true);
target.dispatchEvent(new Event("x"));
console.log("end");
Text
handler
end

The first removal did not match, because it asked for the bubble registration, so the listener stayed. The second, with true, removed it. Only capture matters for matching. The other options, once, passive and signal, do not.

once: remove after the first call

{ once: true } removes the listener automatically after it runs once, which is exact for "the first time" behavior such as an intro animation, a first-interaction hook or a one-shot load wait.

once.jsJavaScript
const button = document.createElement("button");
document.body.append(button);

button.addEventListener("click", () => console.log("first click only"), { once: true });

button.click();
button.click();
Text
first click only

The listener is removed before it is called, so a second event during the handler does not run it again. It also removes the need to keep a reference.

signal: remove with an AbortController

The most useful option for cleanup is signal. Pass an AbortSignal, and aborting it removes the listener. One controller can own any number of listeners on any number of targets, so a single abort() call cleans up everything a component set up.

signal.jsJavaScript
const controller = new AbortController();
const { signal } = controller;

window.addEventListener("resize", () => console.log("resize"), { signal });
document.addEventListener("keydown", (e) => console.log("key", e.key), { signal });
const timer = setInterval(() => console.log("tick"), 1000);
signal.addEventListener("abort", () => clearInterval(timer));

document.dispatchEvent(new KeyboardEvent("keydown", { key: "a" }));
controller.abort();
document.dispatchEvent(new KeyboardEvent("keydown", { key: "b" }));
console.log("aborted:", signal.aborted);
Text
key a
aborted: true

After abort(), the second key press is ignored, and the interval is cleared through an abort listener on the signal. This pattern works with anonymous functions and arrows, since removal does not depend on identity, and it works for fetch() too, which accepts the same signal, so one controller can cancel a request and its listeners together. Support is wide in current browsers and in Node.js.

A component with a clean teardown

Put the pieces together in the shape of a small component: it adds listeners when it mounts and removes all of them in one call when it is destroyed.

component.jsJavaScript
function createDropdown(root) {
  const controller = new AbortController();
  const { signal } = controller;
  const toggle = root.querySelector("button");
  const menu = root.querySelector("ul");

  toggle.addEventListener("click", () => (menu.hidden = !menu.hidden), { signal });

  document.addEventListener(
    "click",
    (event) => {
      if (!root.contains(event.target)) menu.hidden = true;
    },
    { signal },
  );

  document.addEventListener(
    "keydown",
    (event) => {
      if (event.key === "Escape") menu.hidden = true;
    },
    { signal },
  );

  return { destroy: () => controller.abort() };
}

document.body.innerHTML = "<div id='dd'><button>Menu</button><ul hidden></ul></div>";
const dropdown = createDropdown(document.querySelector("#dd"));
dropdown.destroy();
console.log("destroyed");
Text
destroyed

The two document-level listeners are the dangerous ones, since they outlive the element: without destroy(), each time the component is created and thrown away, another pair of listeners stays on the document, holding a reference to its root, and the leak grows. The element-level listener would be collected with the element, which is why the leak is always on the long-lived target: window, document, a shared parent or an EventTarget that outlives the component.

Event delegation: fewer listeners to manage

A list of a thousand rows with a listener on each row is a thousand registrations to add and remove. Put one listener on the container and use event.target.closest() to find the row.

delegation.jsJavaScript
const list = document.createElement("ul");
list.innerHTML = "<li data-id='1'>one</li><li data-id='2'>two</li>";
document.body.append(list);

list.addEventListener("click", (event) => {
  const item = event.target.closest("li");
  if (!item || !list.contains(item)) return;
  console.log("row", item.dataset.id);
});

const added = document.createElement("li");
added.dataset.id = "3";
added.textContent = "three";
list.append(added);

added.click();
Text
row 3

The row added later is handled with no new listener, and when rows are removed there is nothing to clean up. Delegation works for events that bubble, which is most of them, and not for a few such as focus, blur, load, scroll on elements and mouseenter, for which you use capture, or the bubbling variants focusin, focusout and mouseover.

passive for scroll and touch

A listener for touchstart, touchmove or wheel that might call preventDefault() makes the browser wait for it before scrolling, which causes jank. If your handler never cancels, say so with { passive: true } and the browser scrolls without waiting.

passive.jsJavaScript
window.addEventListener(
  "wheel",
  (event) => {
    console.log("wheel", event.deltaY);
  },
  { passive: true },
);
Text
wheel 100

Calling preventDefault() inside a passive listener does nothing and logs a warning. The browser makes touchstart, touchmove and wheel listeners on window, document and body passive by default, so set { passive: false } explicitly on the one element that needs to cancel the scroll.

Handlers, this and arguments

Inside a listener written as a regular function, this is the element the listener is attached to, which is the same as event.currentTarget. In an arrow function, this is whatever it was where the arrow was defined, so use event.currentTarget when you need the element. A class method passed as a listener loses its this, so bind it once, in the constructor or with a class field arrow, and keep that bound reference for removal.

bind.jsJavaScript
class Counter {
  count = 0;

  constructor(button) {
    this.button = button;
    button.addEventListener("click", this.onClick);
  }

  onClick = () => {
    this.count += 1;
    console.log(this.count);
  };

  destroy() {
    this.button.removeEventListener("click", this.onClick);
  }
}

const button = document.createElement("button");
const counter = new Counter(button);
button.click();
button.click();
counter.destroy();
button.click();
Text
1
2

The class field onClick is an arrow function created once per instance, so the same reference is available for adding and for removing. Writing this.onClick.bind(this) inline at both places would create two different functions and the removal would fail. Another form is an object with a handleEvent method: pass the object itself as the listener, and this inside handleEvent is the object, which gives the same identity for both calls without binding.

handle-event.jsJavaScript
const widget = {
  clicks: 0,
  handleEvent(event) {
    this.clicks += 1;
    console.log(event.type, this.clicks);
  },
};

const button = document.createElement("button");
button.addEventListener("click", widget);
button.click();
button.removeEventListener("click", widget);
button.click();
Text
click 1

Finding forgotten listeners

Browser developer tools help. Chrome's Elements panel shows an Event Listeners tab for the selected element, including ones inherited from ancestors, document and window, and the console function getEventListeners(element) lists them. The Memory panel can take a heap snapshot and show detached DOM nodes, which are often held by a forgotten listener. A symptom to watch for is a handler that fires several times for one event after navigating around a single-page app, which means that a listener was added on each visit and never removed.

Testing cleanup

A cleanup test creates the thing, destroys it and checks that no handler runs. Dispatch the events on the long-lived targets, and assert that nothing happens. You can also spy on addEventListener and removeEventListener and compare the calls, or count handler invocations.

test.jsJavaScript
function mount(target) {
  const controller = new AbortController();
  let calls = 0;
  target.addEventListener("ping", () => calls++, { signal: controller.signal });
  return { calls: () => calls, destroy: () => controller.abort() };
}

const target = new EventTarget();
const widget = mount(target);

target.dispatchEvent(new Event("ping"));
widget.destroy();
target.dispatchEvent(new Event("ping"));

console.log(widget.calls());
Text
1

The count is 1, so the second event after destroy() was not handled. Make this kind of test part of every component that touches window, document or a shared emitter.

A checklist

Keep a reference, or use signal, so removal is possible. Use the same capture value to remove. Define handlers once, not inside functions that run repeatedly. Prefer one AbortController per component or feature. Use { once: true } for one-shot handlers. Delegate from a container for lists. Use { passive: true } on scroll and touch listeners that never cancel. Bind class methods once. And always clean up on long-lived targets: window, document, BroadcastChannel, MediaQueryList, WebSocket and observers, which have their own disconnect() or close() calls.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.