JavaScript Events Capture and Bubbling
I wanted to reinforce my understanding of how events work in the browser. While I know how they work, I always find it best to have something to visually represent something that’s inherently abstract, and thus cement it into my head.
Event phases #
There are two phases to events: bubbling and capturing. Any element along the way through the capture and bubbling phases, with the same event listener, will also trigger said event.
Capture Phase #
By default, capturing does not happen in the browser. You have to manually enable it on an event listener like so:
function capture(){
console.log('Capturing');
}
document.querySelector('div').addEventListener('click', capture, { capture: true });
// Shortcut version
// document.querySelector('div').addEventListener('click', capture, true);
Capture goes down from the window
object all the way to the element triggering the event (In this case, a click
event).
Bubble Phase #
Bubbling does the opposite of the capture phase - it goes from the element triggering the event, all the up to the window
.
function bubble(){
console.log('Bubbling');
}
// All events bubble by default
document.querySelector('div').addEventListener('click', bubble);
Event phases demo #
Here we can see the capture and bubble phases, and in what order they trigger. I use the perfomance api to get accurate timestamps for when each event is triggered.
See the Pen Event Capturing and Bubbling by Neal Fennimore ( @nealfennimore) on CodePen.