Event propagation is the process that defines how events travel through the DOM tree when an event occurs. It has three phases:
- Capturing Phase (also called capture phase):
- The event travels from the root (document) down to the target element.
- Target Phase:
- The event reaches the target element where it was triggered.
- Bubbling Phase:
- The event then bubbles back up from the target to the root.
✅ Event Capturing vs Event Bubbling
🔹 Event Capturing (Capture Phase):
- The event moves from the outermost element (document) down to the target element.
- To handle events in this phase, you must pass
{ capture: true }ortrueas the third argument inaddEventListener. - Not used by default.
parent.addEventListener('click', () => {
console.log('Parent - Capturing');
}, true);
🔹 Event Bubbling (Bubble Phase):
- The event moves from the target element up through its parent elements to the root.
- This is the default phase in JavaScript.
- Used widely in event delegation.
child.addEventListener('click', () => {
console.log('Child - Bubbling');
}); // capture = false by default
✅ Summary of Differences (Bullet Form):
- 🔸 Direction:
- Capturing: Top → Down (document → target)
- Bubbling: Bottom → Up (target → document)
- 🔸 Default Behavior:
- Capturing: Not by default
- Bubbling: Happens by default
- 🔸 Syntax:
- Capturing:
addEventListener('click', fn, true) - Bubbling:
addEventListener('click', fn)or withfalse
- Capturing:
- 🔸 Use Case:
- Capturing: Rare; useful to intercept early
- Bubbling: Common; used for delegation
📝 In Summary:
Event propagation explains how events move through the DOM.
Capturing is top-down, bubbling is bottom-up, and both are part of JavaScript’s powerful event-handling system.