When an event occurs on a DOM element, it does not exist in isolation. The event travels through the DOM tree in three distinct phases: the Capturing Phase, the Target Phase, and the Bubbling Phase.
flowchart TD
Window["Window Node"] -->|Phase 1: Capturing Phase (Top Down)| TargetParent["Ancestor Elements (div, body)"]
TargetParent --> Target["Phase 2: Target Phase (Target Element)"]
Target -->|Phase 3: Bubbling Phase (Bottom Up)| Window
| Phase | Flow Direction | Description |
|---|---|---|
| 1. Capturing Phase | Window -> Target Element | Event trickles down from window through ancestors to target. |
| 2. Target Phase | Target Element | Event reaches the actual element that triggered the interaction. |
| 3. Bubbling Phase | Target Element -> Window | Event bubbles back up through ancestors to window (Default listener phase). |
// Demonstrating Event Bubbling and Event Delegation
document.addEventListener("DOMContentLoaded", () => {
const outerBox = document.createElement("div");
outerBox.id = "outer-box";
outerBox.style.padding = "20px";
outerBox.style.background = "#cbd5e1";
const innerBtn = document.createElement("button");
innerBtn.id = "inner-btn";
innerBtn.textContent = "Click Inner Button";
outerBox.appendChild(innerBtn);
document.body.appendChild(outerBox);
// 1. Listener on Child (Target)
innerBtn.addEventListener("click", (event) => {
console.log("1. Inner Button Listener Fired!");
// Uncommenting stops event from bubbling to outerBox:
// event.stopPropagation();
});
// 2. Listener on Parent (Bubbling Phase - Default)
outerBox.addEventListener("click", (event) => {
console.log(`2. Outer Box Bubbling Listener Fired! Target was: ${event.target.id}`);
});
// 3. Listener on Outer Box in Capturing Phase (Third argument true)
outerBox.addEventListener("click", () => {
console.log("0. Outer Box Capturing Listener Fired FIRST!");
}, true); // capture = true
});
event.target vs event.currentTarget: event.target refers to the actual element clicked. event.currentTarget refers to the element processing the current event listener.stopPropagation() Warning: Use event.stopPropagation() sparingly; stopping event propagation can break third-party analytics or global dropdown click handlers.What is the difference between event.target and event.currentTarget during event bubbling?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.