The Difference Between Capturing and Bubbling Phase in JavaScript

The Difference Between Capturing and Bubbling Phase in JavaScript

Ferenc Almasi β€’ Last updated 2020 October 26 β€’ Read time 1 min read
  • twitter
  • facebook
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:

Copied to clipboard! Playground
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('πŸ‘Ά'));
bubbling.js

While in the capturing phase, the opposite happens. The event is captured in the outermost element first and propagates to inner elements:

Copied to clipboard!
// Because of event capturing, this will return β€œπŸ‘¨, πŸ‘Άβ€
ul.addEventListener('click', () => console.log('πŸ‘¨'), true);
li.addEventListener('click', () => console.log('πŸ‘Ά'), true);
capturing.js

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:

What is the difference between event delegation and bubbling?
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

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:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.