Understanding Event Bubbling and Capturing in JavaScript

Understanding Event Bubbling and Capturing in JavaScript

In JavaScript, when an event is triggered on an element, it doesn’t just stop there. It follows a path through the DOM that includes both capturing and bubbling phases:

  1. Capturing Phase: The event starts from the document and travels down through the ancestors to the target element. This phase allows you to intercept events before they reach the intended target.
  2. Target Phase: This is where the event reaches the target element where it was originally triggered.
  3. Bubbling Phase: After reaching the target element, the event travels back up through the ancestors, from the target element to the document. This is the default phase most developers use to handle events.

Example

<div>
    <ul>
        <li></li>
    </ul>
</div>
        

In the structure above, assume that a click event occurred in the li element.

In capturing model, the event will be handled by the div first (click event handlers in the div will fire first), then in the ul, then at the last in the target element, li.

In the bubbling model, the opposite will happen: the event will be first handled by the li, then by the ul, and at last by the div element.

Using these techniques effectively can make your event handling more efficient and your code more maintainable.

Trần Đông Thạnh

⚡Database Administrator | SQL, Oracle Database ⚡

8mo

Good to know

To view or add a comment, sign in

More articles by Lê Anh Ngọc

Insights from the community

Others also viewed

Explore topics