Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 25 min · revision 3

Listeners, Propagation and Default Actions

Register handlers with addEventListener, follow an event down and back up the tree, cancel default actions, and point one listener at many elements.

Contentsand lesson path

What you will learn

  • Handle user input with addEventListener, explaining capture, bubbling and default actions, and use event delegation for dynamic lists.

Prerequisites: JavaScript Foundations

01. Why it matters

So far the pages you have scripted ran top to bottom, once. Interactivity means the same code runs later, on demand, when the user does something — clicks a button, presses a key, submits a form. The browser tells your code about these moments by creating an event object and delivering it to functions you registered: listeners.

Three facts about this system cover most of the confusion beginners hit. First, one event usually visits several elements, not just the one clicked — the order is the propagation model. Second, many interactions have a default action you must cancel on purpose. Third, one listener can serve any number of elements, including ones created after the listener was registered — event delegation. Get these three right and event handling stops feeling like folklore.

02. Listening with addEventListener

A listener is a function plus an event name, attached to a node. When the event happens on that node — or reaches it, as you will see below — the browser calls the function with the event object as its argument. The two most useful properties on that object are event.target, the element the event originally happened on, and event.currentTarget, the element the listener is attached to. They are the same only when the listener sits on the target itself.

You can register several listeners for the same event on the same element; they run in registration order. The event name is the string without the on prefix: click, not onclick.

JavaScript · one event, several listeners
const button = document.querySelector("button");

button.addEventListener("click", (event) => {
  console.log('first listener; target is the button:',
    event.target === button);
});
button.addEventListener("click", () => {
  console.log('second listener runs too');
});

button.click(); // what a user click does
Expected output
first listener; target is the button: true
second listener runs too

03. Propagation: down, at, and back up

A click on a button is also a click on everything that button sits inside. The browser models this with three phases. In the capture phase the event travels from the top of the tree (window) down to the target; listeners registered with addEventListener(name, fn, true) — or an options object { capture: true } — run on the way down. At the target, the element’s own listeners run: its capture listeners first, then the others, each group in registration order. Then the bubble phase carries the event back up, and ordinary listeners run on the way up. event.eventPhase tells a handler which phase it is in.

HTML · three levels deep
<section id="board">
  <ul id="cols">
    <li><button class="card" type="button">Card A</button></li>
  </ul>
</section>
JavaScript · watching the phases
const board = document.querySelector("#board");
const card = document.querySelector(".card");

board.addEventListener('click', () => console.log('board: bubble'));
board.addEventListener(
  'click',
  () => console.log('board: capture'),
  true,
);
card.addEventListener('click', () => console.log('card: target'));
card.addEventListener(
  'click',
  () => console.log('card: target, second'),
);

card.click();
Expected output
board: capture
card: target
card: target, second
board: bubble

The capture listener on board fired first even though it was registered second, because it sits on the way down. Then the button’s two listeners ran in their registration order, then the bubbling listener on board. Not every event bubbles — focus, blur and the scroll event on an element do not — and event.bubbles tells you which you have.

You can interrupt the journey. event.stopPropagation() stops the event from visiting any further elements; it does not cancel anything the browser was going to do. Inside one phase, event.stopImmediatePropagation() also skips the remaining listeners on the same element. Reach for these rarely: propagation is the mechanism that makes delegation work, and handlers that silently swallow events are a common source of "why does nothing happen" bugs.

04. Default actions and preventDefault

Many events carry a built-in consequence that happens after your listeners have run, unless one of them cancels it: submitting a form navigates to its action URL, clicking a link follows the link, pressing Space scrolls the page. (Checkboxes are a special case: the tick changes before your click listeners run, so they already see the new checked value, and preventDefault() puts the old value back afterwards.) That built-in consequence is the default action, and event.preventDefault() is the call that cancels it. It changes nothing about propagation — other listeners still run.

The form case is the one you will meet first. Without any JavaScript, submitting this form would throw away the page and navigate away; the typed email would vanish. With preventDefault, the page stays and your code decides what happens next. Here is the markup the next two demos use, added below the board:

HTML · a sign-up form and a filter box
<form id="signup">
  <label for="email">Email</label>
  <input id="email" name="email" type="email" required>
  <button type="submit">Join</button>
</form>
<p id="status" role="status"></p>

<label for="filter">Filter</label>
<input id="filter" type="text">
JavaScript · keeping the page on a submit
const form = document.querySelector("#signup");
const note = document.querySelector("#status");

form.addEventListener("submit", (event) => {
  event.preventDefault(); // stop the navigation, keep the page
  note.textContent = `Checking ${form.email.value}…`;
  console.log('submit handler ran');
  console.log('input value kept:', form.email.value);
});
Expected output (page console after pressing the Join button)
submit handler ran
input value kept: [email protected]

After the handler, the status line under the form read "Checking [email protected]…" and the page was still there — the URL unchanged, the input still filled. Note the design, too: the status paragraph has role="status", so screen readers announce updates; a labelled input, a real submit button and native validation stay in place. Cancelling the default action does not excuse you from keeping the form accessible.

One performance footnote: for the events that can stop a scroll — wheel, touchstart and touchmove — the browser must wait for your listener before it scrolls, unless you register it as { passive: true }, which promises you will never call preventDefault. (The scroll event itself cannot be cancelled, so the option changes nothing there.) Browsers already default to passive for those events on window, document, the root element and body, so the practical rule is: do not call preventDefault in wheel or touch handlers unless you truly mean to block scrolling, and say so explicitly with { passive: false } when you do.

05. Keys, and one listener for many elements

Keyboard input arrives through keydown (and keyup), carrying event.key — the character or named key such as Escape, Enter or ArrowDown. Check event.key for the keys you handle and leave the rest alone: interfering with Tab, or with the Enter and Space behaviour of a focused button, breaks keyboard users. A common, kind pattern is letting Escape clear or dismiss something:

JavaScript · Escape clears the filter input
const filter = document.querySelector("#filter");

filter.addEventListener("input", () => {
  console.log('input event, value:', JSON.stringify(filter.value));
});

filter.addEventListener("keydown", (event) => {
  if (event.key !== 'Escape') return;
  filter.value = '';
  filter.dispatchEvent(new Event('input'));
  console.log('cleared with Escape');
});
Expected output (after typing "ap", then pressing Escape)
input event, value: "a"
input event, value: "ap"
input event, value: ""
cleared with Escape

The input event fires for every value change — typed, pasted or set by your own code after dispatchEvent. Reusing it from the key handler, instead of duplicating the filter logic there, is the same "single source of truth" idea you will meet again in the lab.

Now imagine that list of cards growing and shrinking. Attaching a click listener to every card means re-attaching for every card added later. Event delegation attaches one listener to a stable ancestor and lets propagation do the walking. Inside the handler, event.target is whatever was actually clicked — possibly an element inside the button — and event.currentTarget is the ancestor. closest(selector) climbs from the target to the nearest matching ancestor, which turns "which card?" into one call:

JavaScript · one listener, current and future buttons
const cols = document.querySelector("#cols");

cols.addEventListener("click", (event) => {
  const button = event.target.closest("button");
  if (!button) return; // the click landed on the list itself
  console.log('clicked:', button.textContent);
  console.log('target is the button:', event.target === button);
  console.log('currentTarget is the list:',
    event.currentTarget === cols);
});

// A new card joins the list later, with no listener of its own.
const li = document.createElement('li');
const fresh = document.createElement('button');
fresh.type = 'button';
fresh.textContent = 'Card B';
li.append(fresh);
cols.append(li);
fresh.click();
Expected output
clicked: Card B
target is the button: true
currentTarget is the list: true

The button that fired had no listener at all; the one listener on cols served it, because the click bubbled up to the list. The lab builds its whole interface this way.

06. Check your understanding

Practice check · 3 questions

Events in the wild

Choose the right tool for three situations.

Q1. A button opens a menu. A separate listener on `document` closes the menu when the user clicks anywhere else. As it stands, the opening click also reaches `document`, so the menu closes at once. What is the smallest correct fix inside the button’s own handler?
Q2. One listener is attached to `ul#menu` and handles clicks on the links inside its items. Inside that handler, `event.currentTarget` is:
Q3. In a handler added with `addEventListener`, the last line is `return false`. What does that achieve?
Practice only: not graded, not saved, not evidence.

07. Apply it

Take the page you built in the previous lesson and give it its first real behaviour, the kind the shopping-list practice will need:

  1. Add a submit form whose handler calls event.preventDefault() and logs the trimmed input value.
  2. Attach one click listener to the list container that uses closest("button") and logs which button was clicked.
  3. Add a keydown listener so Escape clears the form input.
  4. Add a capture-phase listener on document for click that only logs event.eventPhase — watch the numbers it reports, then remove it.

08. Review prompt

Without looking back: name the three phases of event propagation and say how a listener opts into each. What is the difference between event.target and event.currentTarget, and where does closest() fit in? Give three default actions you can cancel, and name the one call that cancels them. Why does delegation need bubbling to work?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check