Events & Event Delegation
Respond to clicks and key presses with well-scoped listeners, then handle repeated items through delegation.
By the end, you’ll be able to…
- Register and remove event listeners with named handler functions.
- Explain bubbling, capturing, event.target, and event.currentTarget.
- Use one delegated listener to handle actions on a dynamic list.
- Support keyboard interaction and clean up listeners when a component is removed.
01Register a listener
addEventListener connects an event type to a function. The browser calls that function whenever the event occurs on the target. Give the handler a name when you may need to remove it, and keep the registration close to the element setup. A page can have many listeners; the goal is one clear responsibility per listener rather than a single function that handles every interaction.
The event object describes what happened. It carries the target, the current element, mouse or key details, and methods such as preventDefault. Read only the properties you need. Logging the whole event in development is fine, but production handlers should stay small: read the event, update state, then let a render function update the page.
02Bubbling, capturing, and default actions
After an event fires on its target, it bubbles upward through ancestors. A listener on a list therefore sees clicks on its items. Capturing runs from the outside in before the target phase; pass true or { capture: true } to listen during that phase. Most application code uses bubbling because it matches the way interfaces are composed.
event.target is the element that triggered the event; event.currentTarget is the element whose listener is running. They differ when you listen on a parent. preventDefault stops the browser's built-in action, such as submitting a form or following a link, without stopping propagation. stopPropagation prevents ancestors from hearing the event, so use it sparingly; it can break other components.
03Delegate repeated items
A list with a delete button on every row could have one listener per button. Delegation replaces them with one listener on the list. Inside the handler, check whether the click started on a delete control, then find the row with closest. This works for rows added later because the listener belongs to the stable parent, not to the individual buttons.
Use data attributes to carry the row id, and read them from the element that matched. Guard against a click that lands on the list itself. closest can return null, so check it. Keep the handler's job narrow: identify the action, then call a function such as removeTodo(id). That separation makes the behaviour testable and easy to extend with edit or complete actions.
04Keyboard events and cleanup
keydown fires when a key goes down. Check event.key for readable values such as Enter, Escape, or ArrowDown. Do not assume every user has a mouse: make controls real buttons, keep focus visible, and support Escape for dismissing overlays. If you handle a key that has a native meaning, call preventDefault only when your custom behaviour is genuinely better.
removeEventListener needs the same function reference and capture setting used during registration. An inline arrow cannot be removed later because it is a different object. For components that mount and unmount, track handlers or pass an AbortSignal to addEventListener and call controller.abort() during cleanup. Removing listeners prevents duplicate work and releases references to detached DOM.
The ideas worth keeping.
- Listen for a named event on a specific element and keep the handler focused on one responsibility.
- Use target to see what was clicked and currentTarget to know where the listener lives.
- Delegate repeated actions to a stable parent, and clear listeners with the same reference or an AbortSignal.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: One listener for a vote list
The page contains a ul with id votes. Each li has a data-id, a button with data-action='vote', and a strong element showing the current count. Add one listener to the list that increments the count for the clicked row and logs the row id and new total. Do nothing when another part of the row is clicked.
Explore a worked solution
const votes = document.querySelector("#votes");votes.addEventListener("click", (event) => { const button = event.target.closest("button[data-action='vote']"); if (!button) return; const item = button.closest("li"); const output = item.querySelector("strong"); const next = Number(output.textContent) + 1; output.textContent = String(next); console.log("Voted for", item.dataset.id, next);});The listener belongs to the list, so rows added later work without new registrations. closest identifies the control and then the row, and Number converts the displayed text before arithmetic.
Exercise 2: Add a removable save shortcut
Write a function enableSaveShortcut(onSave) that listens for Ctrl+S or Cmd+S on the document, prevents the browser's save dialog, and calls onSave. It must return a cleanup function that removes the listener using AbortController. Then create a shortcut that logs 'Draft saved' and store its cleanup function.
Explore a worked solution
function enableSaveShortcut(onSave) { const controller = new AbortController(); document.addEventListener("keydown", (event) => { if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") { event.preventDefault(); onSave(); } }, { signal: controller.signal }); return () => controller.abort();}const stopShortcut = enableSaveShortcut(() => console.log("Draft saved"));The handler checks both the modifier and the key, so an ordinary S does not trigger it. Returning the abort function gives the caller an explicit way to release the listener.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: One listener for a vote list
The page contains a ul with id votes. Each li has a data-id, a button with data-action='vote', and a strong element showing the current count. Add one listener to the list that increments the count for the clicked row and logs the row id and new total. Do nothing when another part of the row is clicked.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.