Event Bubbling and Capturing


When an event happens on an element, it does not stay only on that element. It travels through the DOM in a specific order. This process is called event propagation.

There are two main phases of event propagation:

  • Bubbling
  • Capturing

Understanding how events move through elements helps developers control how and where their code runs.

Bubbling vs Capturing

Bubbling:
The event starts from the target element and moves upward to parent elements.

Capturing:
The event starts from the top (document) and moves down to the target element.

By default, JavaScript uses bubbling.

Here, the button is inside a div. When the button is clicked, the event can affect both the button and the parent div.

When the button is clicked, the event first runs on the button and then moves up to the div.

This is called event bubbling.

The third parameter true enables capturing mode.

By understanding bubbling and capturing, students gain better control over event handling and can build more efficient and predictable JavaScript applications.