TExcelTAD
Home › JavaScript › DOM Event Listeners

DOM Event Listeners

addEventListener is the standard way to react to events. Unlike onclick attributes or properties, it allows any number of handlers per event, keeps JavaScript out of your HTML, supports options such as "run only once", and can be undone with removeEventListener.

Syntax

js
element.addEventListener(type, handler, options);
element.removeEventListener(type, handler, options);
  • type — the event name without "on": "click", not "onclick".
  • handler — a function that receives the event object.
  • options — optional object: { once, capture, passive, signal }.

Several listeners on one element

Listeners run in the order they were added. Assigning onclick would replace the previous handler; addEventListener adds to the list:

html · try it yourself
<button id="btn">Click me</button>
<script>
  const btn = document.getElementById("btn");

  btn.addEventListener("click", () => console.log("listener 1: log the click"));
  btn.addEventListener("click", () => console.log("listener 2: update a counter"));

  btn.onclick = () => console.log("onclick A");
  btn.onclick = () => console.log("onclick B (replaced A)");
</script>

Removing listeners

To remove a listener you must pass the same function reference — so define it as a named function or store it in a variable. An inline arrow function can't be removed because you have no reference to it:

html · try it yourself
<button id="start">Start tracking mouse</button>
<button id="stop">Stop</button>
<p id="pos">Mouse position: –</p>
<script>
  const pos = document.getElementById("pos");

  function track(e) {
    pos.textContent = `Mouse position: ${e.clientX}, ${e.clientY}`;
  }

  document.getElementById("start").addEventListener("click", () => {
    document.addEventListener("mousemove", track);
    console.log("tracking on");
  });
  document.getElementById("stop").addEventListener("click", () => {
    document.removeEventListener("mousemove", track);   // same reference
    console.log("tracking off");
  });
</script>

Useful options

Option Effect
once: true the listener removes itself after the first call
capture: true run during the capturing phase (top-down) instead of bubbling
passive: true promise not to call preventDefault() — lets the browser scroll smoothly
signal: controller.signal remove the listener when an AbortController is aborted
html · try it yourself
<button id="claim">Claim your free coupon</button>
<button id="arm">Arm listeners</button>
<button id="disarm">Disarm all</button>
<script>
  document.getElementById("claim").addEventListener(
    "click",
    (e) => {
      e.currentTarget.textContent = "Coupon claimed ✔";
      console.log("this runs only once");
    },
    { once: true }
  );

  let controller;
  document.getElementById("arm").addEventListener("click", () => {
    controller?.abort();
    controller = new AbortController();
    const { signal } = controller;
    document.addEventListener("keydown", (e) => console.log("key:", e.key), { signal });
    document.addEventListener("dblclick", () => console.log("double click!"), { signal });
    console.log("armed: press keys or double-click");
  });
  document.getElementById("disarm").addEventListener("click", () => {
    controller?.abort();       // removes every listener registered with that signal
    console.log("disarmed");
  });
</script>

Event delegation

Instead of attaching a listener to every item in a list, attach one listener to the parent and use event.target (with closest) to find out which item was clicked. Thanks to bubbling, this works even for items added later:

html · try it yourself
<style>
  li { padding: 4px 0; } li.done span { text-decoration: line-through; color: #888; }
  button.del { margin-left: 8px; }
</style>
<ul id="todos">
  <li><span>Water the plants</span><button class="del">✕</button></li>
  <li><span>Read a chapter</span><button class="del">✕</button></li>
</ul>
<button id="add">Add a task</button>
<script>
  const list = document.getElementById("todos");
  let n = 0;

  list.addEventListener("click", (e) => {
    const li = e.target.closest("li");
    if (!li) return;                                  // clicked the list's padding
    if (e.target.matches("button.del")) {
      console.log("deleted:", li.querySelector("span").textContent);
      li.remove();
    } else {
      li.classList.toggle("done");
    }
  });

  document.getElementById("add").addEventListener("click", () => {
    const li = document.createElement("li");
    li.innerHTML = '<span></span><button class="del">✕</button>';
    li.querySelector("span").textContent = `New task ${++n}`;
    list.append(li);                                  // no new listener needed
  });
</script>

Benefits of delegation: fewer listeners (less memory), no need to attach handlers to new elements, and one central place for the list's logic.

this and arrow functions in listeners

With a regular function, this inside the handler is the element the listener is attached to (event.currentTarget). Arrow functions don't change this, so use event.currentTarget there — it's clearer anyway.

Tip: Avoid inline onclick="…" attributes in real projects. They mix code into markup, can only reference global functions, and are blocked by strict Content-Security-Policy settings.

Test yourself

Why can't you remove el.addEventListener("click", () => go()) with removeEventListener?

  1. Arrow functions can't be listeners
  2. You need the same function reference, and the inline arrow has none
  3. removeEventListener only works on window
  4. Click listeners can't be removed

Which option makes a listener run at most one time?

  1. { single: true }
  2. { once: true }
  3. { passive: true }
  4. { capture: true }

What is event delegation?

  1. Handling events of many children with one listener on a common ancestor
  2. Passing events to a Web Worker
  3. Calling preventDefault on every event
  4. Adding a listener to each child element