An event travels through the page in three phases: down to the element (capture), at the element (target), and back up (bubble). Event delegation uses the bubble phase to handle many children with one listener.
The three phases:
- Capture: the event goes from
windowdown through the ancestors to the target. - Target: the event reaches the element itself.
- Bubble: the event goes back up from the target to
window.
Listeners run in the bubble phase by default. To run in the capture phase, pass { capture: true } (or just true) to addEventListener.
Some events, like focus, do not bubble.
Event delegation: instead of adding a listener to every child, add one listener to a shared parent. Then check event.target to see which child was clicked. Often you use event.target.closest('li') for this.
For example, a to-do list can have one listener on the <ul> instead of one on each <li>. This uses less memory. It also works automatically for children added later, such as new rows in a dynamic list.
- An event has three phases: capture (going down), target, and bubble (going up).
- Listeners run in the bubble phase by default. Use
capture: truefor the capture phase. - Not all events bubble.
focusandblurdo not. - Delegation means one listener on a parent that checks
event.target. - Delegation also works for elements added later.