Lesson 11 of 28
In progress
Events and event delegation
Listen for clicks, typing and keyboard input, understand bubbling, and use one handler for a whole list.
An event is the browser telling you that something happened. Your job is to listen for the ones you care about, do the smallest useful thing, and not break the browser’s built-in behaviour in the process.
What you will learn
- Attach and remove listeners.
- Read the event object and stop a default action.
- Handle events from many children with one delegated listener.
addEventListener
Editable. Runs in your browser.
<script>
const button = document.querySelector("#save");
const out = document.querySelector("#out");
function handleSave() {
out.textContent = "Saved at " + new Date().toLocaleTimeString();
}
button.addEventListener("click", handleSave);
</script>
Press Run to see the output.
addEventListener takes an event name and a function. The function runs later, when the event happens, which is why it is a callback. Using a named function also lets you remove it:
button.removeEventListener("click", handleSave);
An anonymous arrow cannot be removed, because you no longer hold a reference. In long-lived pages, listeners that are never removed keep their elements and closures alive.
Do not use the onclick attribute in HTML. It mixes behaviour into markup, allows only one handler, and is blocked by a strict Content Security Policy.
The event object
Editable. Runs in your browser.
<script>
document.querySelector("#go").addEventListener("click", (event) => {
console.log(event.type);
console.log(event.target.tagName);
console.log(event.target.dataset.id);
});
</script>
Press Run to see the output.
event.target is the element that triggered the event. event.currentTarget is the element the listener is attached to; they differ when the event bubbles from a child. event.type is the name.
For keyboard events, check event.key ("Enter", "Escape") rather than the deprecated keyCode. For form events, event.target gives you the field.
Default actions and bubbling
Some events have a browser default: a link navigates, a form submits, a checkbox toggles. preventDefault cancels that default without stopping anything else.
Editable. Runs in your browser.
<script>
document.querySelector("#link").addEventListener("click", (event) => {
event.preventDefault();
console.log("Navigation stopped for this demo");
});
</script>
Press Run to see the output.
Events bubble from the target up through its ancestors. A click on a button inside a card reaches the button, then the card, then the document, unless something stops it. stopPropagation prevents that climb, and it is usually a mistake: it breaks delegation and other listeners that expected to see the event.
Delegation
Instead of adding a listener to every item, add one to the container and use target.closest to find the item.
Editable. Runs in your browser.
<script>
const list = document.querySelector("#tasks");
list.addEventListener("click", (event) => {
const button = event.target.closest("button[data-id]");
if (!button) return;
button.closest("li").classList.toggle("done");
console.log("Toggled", button.dataset.id);
});
</script>
Press Run to see the output.
This survives items added later, because the listener lives on the parent. It also uses less memory than one listener per row. The early return handles clicks on the text, which bubble up without matching the selector.
Keyboard and focus
A click handler on a div does not respond to Enter or Space. Use a real button. When you must listen for keys, handle the specific key and do not swallow every keypress.
Editable. Runs in your browser.
<script>
const search = document.querySelector("#search");
search.addEventListener("keydown", (event) => {
if (event.key !== "Enter") return;
document.querySelector("#echo").textContent = `Searching for: ${search.value}`;
});
</script>
Press Run to see the output.
input fires on every change and is right for live filtering. change fires when the field loses focus, which suits validation. submit on the form is better than a click on the button, because it also covers pressing Enter.
Performance details
Scroll and resize handlers run very often. If the work is expensive, throttle it with requestAnimationFrame or a timer rather than doing layout on every event.
Measure before optimising, because a handler that does very little is fine at any frequency. { passive: true } tells the browser you will not call preventDefault, which lets it scroll immediately. It matters for touch and wheel handlers, less for clicks.
Adding a listener inside a loop or inside a render function without removing the old one stacks handlers, so one click runs the same code five times. Either delegate from a stable parent or keep a reference and remove before adding.
Build a list of three buttons. Use one delegated listener to mark the clicked item active, and log the item’s id from a data attribute. Ensure clicking the list background does nothing.
Show solution
Editable. Runs in your browser.
<script>
const menu = document.querySelector("#menu");
menu.addEventListener("click", (event) => {
const button = event.target.closest("button[data-id]");
if (!button) return;
menu.querySelectorAll("button").forEach((item) => item.classList.remove("active"));
button.classList.add("active");
console.log("Selected", button.dataset.id);
});
</script>
Press Run to see the output.
One listener covers every item, and the closest check ignores clicks that did not land on a button. Removing active from all before adding to one keeps a single selection.
Recap
- Use
addEventListenerwith a named function so it can be removed. preventDefaultcancels browser behaviour; avoidstopPropagationunless you must.- Delegate from a stable parent with
closest, and use formsubmitrather than button clicks.
Next, you will read and validate form input, including the cases the browser does not catch.
Why did my listener run twice?
What is the difference between input and change?
Progress is saved in this browser only. No account, no email.