The Difference Between Capturing and Bubbling Phase in JavaScript
Event bubbling and capturing are two ways events can be handled in the HTML DOM API. When an event occurs in an element and its parent also registers a handle for the same event, the event propagation model will determine which element should receive the event first.
By default, addEventListener
uses bubbling β here the event is first captured in the innermost element and propagates to outer elements:
const ul = document.getElementById('parent');
const li = document.getElementById('child');
// Because of event bubbling, this will return βπΆ, π¨β
ul.addEventListener('click', () => console.log('π¨'));
li.addEventListener('click', () => console.log('πΆ'));
While in the capturing phase, the opposite happens. The event is captured in the outermost element first and propagates to inner elements:
// Because of event capturing, this will return βπ¨, πΆβ
ul.addEventListener('click', () => console.log('π¨'), true);
li.addEventListener('click', () => console.log('πΆ'), true);
As you can see, you can change the even propagation mode for addEventListener
, by setting the second parameter (useCapture
) to true
.
You can check out the differences at the following pen, change the flag to use bubbling instead of capturing:
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: