Event Bubbling & Capturing
The Ninja Clan Hierarchy
Imagine a scenario in a ninja clan where a message needs to be passed through the ranks. The message (event) can travel in two directions: from the top (grandmaster) to the bottom (new recruits) or vice versa. In event capturing, the message is passed down from the grandmaster to the recruits, and in event bubbling, the message travels up from the recruits to the grandmaster.
Whispers Through the Pagoda
Whispers rise and fall,
Through the clan, messages weave,
Bubbling, capturing
Pagoda Event Flow
// Define a pagoda with three levels: grandmaster, sensei, and recruit
const grandmaster = document.getElementById('grandmaster');
const sensei = document.getElementById('sensei');
const recruit = document.getElementById('recruit');
// Event capturing: Grandmaster hears the news first
grandmaster.addEventListener('message', (event) => {
console.log('Grandmaster received the message during capturing phase');
}, true); // true sets the listener to capture phase
// Event bubbling: Recruit's message bubbles up
recruit.addEventListener('message', (event) => {
console.log('Recruit sends a message that bubbles up');
});
// Simulate a message event triggered by the recruit
recruit.dispatchEvent(new Event('message', {bubbles: true}));
Closure
Bubble Up, Capture Down
Events bubble up from the target element towards the root, and capture down from the root to the target.
Concept Checking Questions
-
What will happen if an event is triggered at the
sensei
level and there are listeners for this event on all three levels (grandmaster, sensei, recruit) in the bubbling phase?- The event handler on the sensei will trigger first, then the event will bubble up to the grandmaster. The recruit will not be affected since the event bubbles up, not down.
-
If you want to stop an event from bubbling up beyond the
sensei
level, what method can you use inside the sensei's event handler?- You can use
event.stopPropagation()
within the sensei's event handler to prevent the event from bubbling up further.
- You can use
-
Can an event be both captured and bubbled at the same time? How would you set up listeners to observe this?
- Yes, an event can go through both phases. To observe this, you can set up listeners on the same element for both capturing (by setting the third argument to
true
) and bubbling (by omitting the third argument or setting it tofalse
).
- Yes, an event can go through both phases. To observe this, you can set up listeners on the same element for both capturing (by setting the third argument to