What is addEventListener?

target.addEventListener(type, listener, options) registers a function to run when an event of that type happens on a DOM element, document, window or any other EventTarget; you can add many listeners for the same event.

Options

  • once: true: run the listener a single time, then remove it automatically.
  • passive: true: promise not to call preventDefault(). Browsers can then scroll immediately, which makes touchstart, touchmove and wheel listeners smoother.
  • capture: true: listen in the capture phase instead of the bubble phase.
  • signal: an AbortSignal; calling controller.abort() removes every listener registered with it. This is the cleanest way to clean up many listeners at once (for example when a component unmounts).

Removing listeners

removeEventListener(type, sameFunction, sameCaptureFlag) needs the exact same function reference, so inline arrow functions cannot be removed. Keep a reference, or use signal.

Compared to onclick

element.onclick = fn holds only one handler; assigning again replaces it. addEventListener supports multiple handlers and the options above.

Inside the listener

  • event.target (origin) vs event.currentTarget (the element the listener is on).
  • event.preventDefault() stops default behaviour (form submit, link navigation).
  • With a normal function, this is currentTarget; with an arrow function, use event.currentTarget.

Custom events

target.dispatchEvent(new CustomEvent("cart:add", { detail: {...} })) lets parts of your app communicate through the DOM.

Code example

js
1document.body.innerHTML = `<button id="save">Save</button> <a id="link" href="https://example.com">Link</a>`;
2const save = document.getElementById("save");
3const log = [];
4
5// Multiple listeners on the same event
6save.addEventListener("click", () => log.push("validate"));
7save.addEventListener("click", () => log.push("save"));
8
9// once: removed automatically after the first run
10save.addEventListener("click", () => log.push("first-click analytics"), { once: true });
11
12save.click();
13save.click();
14console.log(log); // ["validate", "save", "first-click analytics", "validate", "save"]
15
16// Remove many listeners at once with an AbortController
17const controller = new AbortController();
18window.addEventListener("resize", () => {}, { signal: controller.signal });
19document.addEventListener("keydown", () => {}, { signal: controller.signal });
20controller.abort(); // both removed
21
22// preventDefault: stop link navigation
23document.getElementById("link").addEventListener("click", (e) => {
24 e.preventDefault();
25 console.log("navigation prevented for", e.currentTarget.href);
26});
27document.getElementById("link").click();
28
29// Custom events
30document.addEventListener("cart:add", (e) => console.log("added to cart:", e.detail.sku));
31document.dispatchEvent(new CustomEvent("cart:add", { detail: { sku: "A1" } }));

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app