JavaScript Reference ยท DOM: Events
Event delegation
Learn event delegation: attach one listener to a parent, use event.target and closest() to find the real element, and handle items added later.
Event delegation means putting one listener on a common ancestor instead of one listener on every child. It works because most events bubble: a click on a list item travels up through the list, so the list can handle it.
This pattern uses less memory, keeps working for elements added later, and keeps your setup code short. The listener decides what to do by looking at event.target.
list.addEventListener("click", (event) => { const item = event.target.closest("li"); if (item && list.contains(item)) { // handle the item } });
Try it
How it works
- A user action happens on a deep element. The browser creates an event with
targetset to that element. - For events that bubble, the event travels up through every ancestor and calls their listeners.
- Your single listener on the container receives the event.
event.currentTargetis the container, andevent.targetis the original element. - You test whether
target(or its closest matching ancestor) is one you care about, and act on it.
Patterns
closest(selector). Climb fromevent.targetto the nearest matching ancestor. This handles clicks on icons and text inside buttons. Always add acontainer.contains(match)check, becauseclosest()can find an ancestor outside your container.data-*attributes. Putdata-action="remove"on buttons and switch onbutton.dataset.action, so a single listener can serve many actions.matches(selector). Fine when the target can only be the element itself, such as an<input>with no children.- Capture-phase delegation. Events that do not bubble, like
focusandblur, can be delegated withfocusin/focusout(which do bubble) or by adding the listener with{ capture: true }.
Usage notes
- Not every event bubbles.
mouseenter,mouseleave,load,focus,blur,scroll(on elements) and others do not. Use their bubbling equivalents (mouseover/mouseout,focusin/focusout) or capture. - Someone may stop propagation. If a child listener calls
stopPropagation(), your delegated handler never runs. - Keep the container close. Listen on the nearest stable ancestor instead of
documentwhen you can, so the handler runs for fewer events. - Do not delegate high-frequency events needlessly. For
mousemoveandscroll, a handler on a large container runs constantly; check the target early and return. - Disabled controls. Clicks on disabled form controls do not fire click events in most browsers, so a delegated handler may not hear them.
Browser support
Event bubbling and closest() are supported in all current browsers. focusin and focusout are supported in current browsers too; check a compatibility table for very old ones.
Related
- event bubbling and capturing โ the mechanism behind delegation
Event.targetandcurrentTargetElement.closest()Event.stopPropagation()- Lesson: Event delegation
- Lesson: Events