JavaScript Propagation & Delegation
In the DOM, events don't just happen to a single element. They flow through the document tree. Understanding this flow is crucial for writing performant, scalable JavaScript.
The 3 Phases of Event Flow
When an event occurs, it travels in three distinct phases:
- 1. Capturing Phase: The event travels DOWN from the root document to the target element.
- 2. Target Phase: The event reaches the exact element that was interacted with.
- 3. Bubbling Phase: The event travels UP from the target element back to the root.
Event Bubbling & stopPropagation
Because of the Bubbling Phase, clicking a child element (like a button inside a div) will also trigger the click listener of the parent div. You can stop this upward journey by calling event.stopPropagation() on the event object.
Event Delegation
Instead of attaching 100 event listeners to 100 list items (which wastes memory), you can attach ONE listener to the parent <ul>. Thanks to bubbling, clicks on the list items will travel up to the parent listener.
"Use event.target to identify the specific child element that was clicked, and event.currentTarget to reference the parent element the listener is attached to."
