Skip to content

Lesson 22 of 50JavaScript in the browser

DOM Events

React to clicks, typing and key presses with addEventListener, understand bubbling, and handle whole lists with one listener.

16 min read0/4 questions

A page that only changes when it loads is not very interactive. Events are how the browser tells your code that something happened: a click, a key press, a form being submitted, the page finishing loading. You register a function, the browser calls it when the event fires, and your function updates the DOM. That simple loop powers every button, menu and search box on the web, and "explain event delegation" is one of the most common front-end interview questions.

Listening for an event

You attach a listener (also called a handler: a function that waits for an event) with addEventListener. It takes the event type as a string and the function to call:

button.addEventListener("click", () => {
  console.log("clicked");
});

Read it as "when this button is clicked, run this function". Note that you pass the function itself; you do not call it. addEventListener("click", save()) would run save immediately, once, and register whatever it returned.

You may see older code with onclick="save()" written in the HTML, or button.onclick = save in JavaScript. Both work, but addEventListener is preferred: it keeps JavaScript out of your HTML, and it lets several independent listeners share one event instead of overwriting each other.

HTML & CSS
<style> .counter { display: flex; gap: 8px; align-items: center; font-size: 20px; } button { font-size: 18px; width: 40px; height: 40px; }</style> <div class="counter"> <button id="minus" aria-label="Remove one">-</button> <output id="count">0</output> <button id="plus" aria-label="Add one">+</button></div> <script> let count = 0; const display = document.getElementById("count"); function render() { display.textContent = count; } document.getElementById("plus").addEventListener("click", () => { count += 1; render(); }); document.getElementById("minus").addEventListener("click", () => { count = Math.max(0, count - 1); render(); });</script>

Preview

Click both buttons. Then make the plus button add 5, or stop the count at 10 with Math.min. Notice the shape: the data lives in a variable (count), handlers change the data, and one render function makes the page match. You will use that shape again in the project lesson.

The event object

When the browser calls your listener, it passes one argument: an event object describing what happened. The usual name for it is event or e. The most useful parts:

Property or methodWhat it tells you
event.typeThe event name, like "click" or "keydown"
event.targetThe element where the event started (what was actually clicked or typed in)
event.currentTargetThe element whose listener is running right now
event.keyFor keyboard events: the key, like "Enter", "Escape", "a"
event.preventDefault()Stop the browser's built-in action (following a link, submitting a form)
event.stopPropagation()Stop the event travelling further up the tree

And the events you will reach for most:

EventFires when
clickAn element is clicked, tapped, or activated with Enter or Space on a button
inputThe value of a field changes, on every keystroke
changeA field's value is committed: a checkbox ticks, a select changes, a text field loses focus
submitA form is submitted, by a submit button or by pressing Enter in a field
keydown / keyupA key goes down or comes up
focus / blurAn element gains or loses focus (these two do not bubble; focusin and focusout do)
DOMContentLoadedThe HTML is fully parsed and the DOM is ready

Here are input and keydown together in a short post composer:

HTML & CSS
<style> textarea { width: 100%; height: 80px; font: inherit; } .over { color: #b91c1c; font-weight: bold; }</style> <label for="post">What are you working on?</label><textarea id="post"></textarea><p id="left">40 characters left</p><p id="last-key">Last key: none</p> <script> const MAX = 40; const post = document.getElementById("post"); const left = document.getElementById("left"); post.addEventListener("input", (event) => { const remaining = MAX - event.target.value.length; left.textContent = `${remaining} characters left`; left.classList.toggle("over", remaining < 0); }); post.addEventListener("keydown", (event) => { document.getElementById("last-key").textContent = `Last key: ${event.key}`; if (event.key === "Escape") post.value = ""; });</script>

Preview

Type past 40 characters and watch the counter turn red. Press Escape to clear the box (the counter does not update, because setting value from code does not fire input; try calling post.dispatchEvent(new Event("input")) after clearing). Then change "input" to "change" in the first listener and notice it now only updates when you click away.

Match the pairs0/4 matched

Match each goal to the event to listen for.

Choose an item, then its match on the other side.

Bubbling: events travel up the tree

When you click a button inside a card inside a list, which element was clicked? All of them, in a sense. An event starts at the element where it happened, the target, and then bubbles: it fires again on the parent, then the grandparent, and so on up to document and window. Any of those elements can listen for it.

(Before bubbling there is also a capture phase, where the event travels down from window to the target. You rarely need it; passing { capture: true } as a third argument to addEventListener listens during that phase instead.)

A click on the Buy button bubbles up
windowbutton.buythe targetli.productul.productsbodydocumentroot

The click happens on the button. Listeners on the button run first. Here event.target and event.currentTarget are both the button.

1/4

You can watch it happen. Every box below has a click listener that writes to the log:

HTML & CSS
<style> div { padding: 14px; border: 2px solid #555; margin: 4px; } #outer { background: #e0f2fe; } #middle { background: #fef3c7; } #inner { background: #fce7f3; } #log { font-family: monospace; white-space: pre; }</style> <div id="outer">outer <div id="middle">middle <div id="inner">inner (click me)</div> </div></div><p id="log"></p> <script> const log = document.getElementById("log"); for (const id of ["outer", "middle", "inner"]) { document.getElementById(id).addEventListener("click", (event) => { log.textContent += `${event.currentTarget.id} heard a click on ${event.target.id}\n`; }); }</script>

Preview

Click the inner box: three lines appear, from the inside out. Click the outer box and only one appears. Then add event.stopPropagation(); inside the listener and click the inner box again.

Quick check
A listener is attached to a ul. The user clicks a span inside an li inside that list. Inside the listener, what are event.target and event.currentTarget?
Need a nudge? A hint rules out a wrong answer.

Event delegation

Imagine a list of 200 products, each with a Remove button. You could add 200 listeners. Or you can add one listener to the list and let bubbling bring every click to it. This is event delegation, and it has two big advantages: fewer listeners, and it works for items added later, which per-button listeners would miss.

The tool that makes it neat is closest(selector): starting from an element, it walks up the tree and returns the nearest ancestor (or the element itself) that matches, or null.

HTML & CSS
<style> li { display: flex; justify-content: space-between; padding: 6px 0; border-bottom: 1px solid #eee; } li button { font-size: 12px; }</style> <ul id="cart"> <li data-id="1">Notebook <button class="remove">Remove</button></li> <li data-id="2">Blue pen <button class="remove">Remove</button></li></ul><button id="add">Add a random item</button><p id="info">2 items</p> <script> const cart = document.getElementById("cart"); let nextId = 3; cart.addEventListener("click", (event) => { const button = event.target.closest("button.remove"); if (!button) return; // the click was somewhere else in the list const item = button.closest("li"); item.remove(); document.getElementById("info").textContent = `Removed item ${item.dataset.id}. ${cart.children.length} left`; }); document.getElementById("add").addEventListener("click", () => { const names = ["Stapler", "Sticky notes", "Ruler", "Highlighter"]; const li = document.createElement("li"); li.dataset.id = nextId++; li.textContent = names[Math.floor(Math.random() * names.length)] + " "; const button = document.createElement("button"); button.className = "remove"; button.textContent = "Remove"; li.append(button); cart.append(li); });</script>

Preview

Add a few items, then remove them. The new items never got their own listener, but their buttons still work, because the click bubbles up to the one listener on cart.

preventDefault: stopping the browser's own action

Many elements come with built-in behaviour: a link navigates, a submit button sends its form and reloads the page, a checkbox ticks. event.preventDefault() cancels that default action while still letting your listener run. Its most common use is a form submit handler that sends data with JavaScript instead of reloading:

form.addEventListener("submit", (event) => {
  event.preventDefault(); // stay on this page
  // read the fields and handle them here
});

preventDefault and stopPropagation are easy to mix up. The first stops the browser's action; the second stops the event's journey up the tree. They are independent. The forms lesson builds on this.

Removing listeners

removeEventListener takes the same type and the same function you added. That means you need a named reference. Passing a new arrow function does nothing, because two arrow functions with the same code are still two different functions.

function onScroll() {
  console.log(window.scrollY);
}
window.addEventListener("scroll", onScroll);
window.removeEventListener("scroll", onScroll); // works
 
button.addEventListener("click", () => save());
button.removeEventListener("click", () => save()); // silently does nothing

Two shortcuts help. { once: true } removes the listener automatically after it runs once. And an AbortController can remove a whole group of listeners in one call, which is handy when a widget is torn down:

const controller = new AbortController();
window.addEventListener("resize", onResize, { signal: controller.signal });
window.addEventListener("keydown", onKey, { signal: controller.signal });
controller.abort(); // both listeners are removed

The order things run in

Listeners on the same element run in the order they were added, and they run synchronously: each one finishes before the next starts. A real click arrives as a task from the event loop, so it waits until your current code is done. But calling button.click() from code dispatches the event immediately, in the middle of whatever you are doing.

Predict the outputJavaScript

What does this print?

const button = document.createElement("button");
let log = "";
button.addEventListener("click", () => { log += "A"; });
button.addEventListener("click", () => { log += "B"; });
log += "C";
button.click();
log += "D";
console.log(log);
Need a nudge? Hints walk you through it.

Because handlers run on the single JavaScript thread, a slow handler freezes the page: no other clicks, no repaints, until it returns. Keep handlers short, and move heavy work out of them.

Quick check
Why does button.removeEventListener('click', () => save()) not remove a listener added with button.addEventListener('click', () => save())?
Need a nudge? A hint rules out a wrong answer.
Key terms
event
A signal from the browser that something happened, such as a click, a key press or a form submit.
listener
A function registered with addEventListener that the browser calls when the event fires.
event.target
The element where the event started, such as the exact element that was clicked.
bubbling
After firing on its target, an event fires on each ancestor in turn, up to the document and window.
event delegation
Handling events for many children with one listener on their parent, using bubbling and closest().
preventDefault
A method on the event that cancels the browser's built-in action, like following a link or submitting a form.