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.
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.
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 method | What it tells you |
|---|---|
event.type | The event name, like "click" or "keydown" |
event.target | The element where the event started (what was actually clicked or typed in) |
event.currentTarget | The element whose listener is running right now |
event.key | For 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:
| Event | Fires when |
|---|---|
click | An element is clicked, tapped, or activated with Enter or Space on a button |
input | The value of a field changes, on every keystroke |
change | A field's value is committed: a checkbox ticks, a select changes, a text field loses focus |
submit | A form is submitted, by a submit button or by pressing Enter in a field |
keydown / keyup | A key goes down or comes up |
focus / blur | An element gains or loses focus (these two do not bubble; focusin and focusout do) |
DOMContentLoaded | The HTML is fully parsed and the DOM is ready |
Here are input and keydown together in a short post composer:
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 each goal to the event to listen for.
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.)
The click happens on the button. Listeners on the button run first. Here event.target and event.currentTarget are both the button.
You can watch it happen. Every box below has a click listener that writes to the log:
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.
ul. The user clicks a span inside an li inside that list. Inside the listener, what are event.target and event.currentTarget?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.
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 nothingTwo 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 removedThe 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.
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);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.
button.removeEventListener('click', () => save()) not remove a listener added with button.addEventListener('click', () => save())?- 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.