Skip to the content

Lesson 88 of 296

Events: bubbling, capturing, delegation, preventDefault

What you will learn

  • Listening for events
  • The event object: target vs currentTarget
  • The three phases: capturing, target, bubbling
  • Stopping events and default actions
  • Event delegation
  • Listener options
  • Common event types and custom events
On this page

Listening for events

An event is something that happens: a click, a key press, a form submission, a page scroll. You react with an event listener:

button.addEventListener("click", (event) => {
  console.log("Clicked!");
});

Avoid the old way, button.onclick = ...: it allows only one handler per event, and a second assignment silently replaces the first.

Removing a listener

You must pass the same function reference:

function handleClick() { console.log("clicked"); }
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);      works

button.addEventListener("click", () => console.log("x"));
button.removeEventListener("click", () => console.log("x"));   does nothing: a different function

The event object

Property / methodMeaning
event.type"click", "keydown" and so on
event.targetThe element where the event started (what was actually clicked)
event.currentTargetThe element whose listener is running now
event.preventDefault()Stop the browser's default action
event.stopPropagation()Stop the event travelling to other elements
event.keyFor keyboard events: "Enter", "Escape", "a"

target vs currentTarget (common interview question):

<div id="card">
  <button>Buy</button>
</div>
card.addEventListener("click", (e) => {
  console.log(e.target);          the <button>, if the button was clicked
  console.log(e.currentTarget);   always the <div id="card">
});

The three phases

When you click a button inside a card inside the body, the event travels:

  1. Capturing phase: from window down through each ancestor to the target.
  2. Target phase: at the clicked element.
  3. Bubbling phase: from the target back up through each ancestor to window.
window -> document -> html -> body -> div#card -> button     (capturing, down)
                                                  button     (target)
window <- document <- html <- body <- div#card <- button     (bubbling, up)

By default, listeners run in the bubbling phase. To run in the capturing phase:

card.addEventListener("click", handler, { capture: true });

Bubbling is why a click on the button also triggers a click listener on the card, the body and the document.

Events that do not bubble

Some events do not bubble: focus, blur, mouseenter, mouseleave, load. Bubbling alternatives exist: focusin and focusout instead of focus and blur; mouseover and mouseout instead of mouseenter and mouseleave.

preventDefault

Stops the browser's built-in action:

EventDefault action
submit on a formSends the form and reloads the page
click on a linkGoes to the URL
click on a checkboxTicks it
keydown in an inputTypes the character
contextmenuOpens the right-click menu
form.addEventListener("submit", async (e) => {
  e.preventDefault();               stay on the page
  const data = new FormData(form);
  await fetch("/api/subscribe", { method: "POST", body: data });
});

Listen for submit on the form, not click on the button. Then pressing Enter in a field also works, and browser validation still runs.

stopPropagation

Stops the event moving on to other elements. The default action still happens.

modalContent.addEventListener("click", (e) => {
  e.stopPropagation();        clicks inside the modal do not reach the backdrop
});

Use it rarely. It breaks other code that relies on bubbling, such as analytics or delegated listeners. Usually you can check event.target instead:

backdrop.addEventListener("click", (e) => {
  if (e.target === backdrop) closeModal();       only when the backdrop itself was clicked
});

stopImmediatePropagation() also stops other listeners on the same element.

preventDefault vs stopPropagation

Stops the browser's default actionStops the event reaching other elements
preventDefault()YesNo
stopPropagation()NoYes

Event delegation

Instead of adding a listener to every child, add one listener to the parent and check which child was clicked. This works because of bubbling.

<ul id="todo-list">
  <li data-id="1">Buy milk <button class="delete">x</button></li>
  <li data-id="2">Call Sam <button class="delete">x</button></li>
</ul>
const list = document.getElementById("todo-list");

list.addEventListener("click", (e) => {
  const deleteButton = e.target.closest(".delete");
  if (!deleteButton) return;
  const item = deleteButton.closest("li");
  console.log("Delete item", item.dataset.id);
  item.remove();
});

Why use delegation:

  • One listener instead of hundreds: less memory.
  • Works for elements added later automatically. With per-item listeners, every new item needs a new listener.
  • Simpler code when lists are re-rendered.

Why closest(): the user might click an icon inside the button, so e.target would be the icon. closest(".delete") walks up to the button.

Listener options

el.addEventListener("click", handler, {
  once: true,          remove automatically after the first call
  passive: true,       promise not to call preventDefault: smoother scrolling for touch and wheel
  capture: true,       run in the capturing phase
  signal: controller.signal    remove when the AbortController is aborted
});

Removing many listeners at once:

const controller = new AbortController();
window.addEventListener("resize", onResize, { signal: controller.signal });
window.addEventListener("scroll", onScroll, { signal: controller.signal });
controller.abort();        removes both

Common events

CategoryEvents
Mouse and pointerclick, dblclick, pointerdown, pointerup, pointermove, mouseover
Keyboardkeydown, keyup
Formsinput (every change while typing), change (when the value is committed), submit, focusin, focusout
Windowscroll, resize, load, DOMContentLoaded, beforeunload

Pointer events handle mouse, touch and pen with one set of events. Prefer them for new code.

Keyboard: use event.key ("Enter", "Escape", "ArrowDown"). keyCode is deprecated.

input vs change: on a text field, input fires on every key stroke; change fires when the field loses focus after a change. For live search, use input (with debounce, Lesson 78).

Custom events

You can create and send your own events:

const event = new CustomEvent("cart:updated", { detail: { count: 3 }, bubbles: true });
cartButton.dispatchEvent(event);

document.addEventListener("cart:updated", (e) => {
  badge.textContent = e.detail.count;
});

Common mistakes

  • Trying to remove a listener with a new anonymous function.
  • Listening for click on the submit button instead of submit on the form.
  • Using e.target when you needed e.currentTarget, or when the click landed on a child element.
  • stopPropagation everywhere.
  • Adding a listener inside a function that runs many times, creating duplicates.

How to say it in an interview

"Events go through a capturing phase down from the window, the target phase, then a bubbling phase back up; listeners run during bubbling by default. target is where the event started and currentTarget is the element whose listener is running. preventDefault stops the browser's default action, like a form submission, and stopPropagation stops the event travelling further, which I use sparingly. Event delegation attaches one listener to a parent and uses event.target.closest to find the child, which saves memory and works for elements added later."

Key words

WordMeaning
EventSomething that happens, such as a click
Event listenerA function that runs when an event happens
target / currentTargetWhere the event started / whose listener is running
CapturingThe event travelling down to the target
BubblingThe event travelling back up from the target
preventDefaultStops the browser's built-in action
stopPropagationStops the event moving to other elements
Event delegationOne listener on a parent for many children
Passive listenerA listener that will not call preventDefault

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.