DEV Community

Ujjawal Kumar
Ujjawal Kumar

Posted on • Updated on

Event Capturing and Event Bubbling in JavaScript: Exploring DOM Event Handling Mechanisms

Event Capturing and Event Bubbling
Event capturing and event bubbling are two different mechanisms through which events are handled in JavaScript. These mechanisms determine the order in which event handlers are executed when an event occurs on an element that is nested within other elements.

Event Capturing (also known as the "capture phase"):

  • In the capture phase, the event is first captured by the outermost element and then propagated inward to the target element.

  • During this phase, the event travels from the top of the DOM hierarchy down to the target element.

  • The capturing phase is not commonly used in practice and is optional in event handling.

Event Bubbling (also known as the "bubble phase"):

  • In the bubbling phase, the event is first handled by the target element's event handler and then propagated upward through the DOM hierarchy.

  • During this phase, the event travels from the target element up to the topmost ancestor.

  • This is the default behavior for most DOM events.

To illustrate the concept, consider the following HTML structure:

<div id="outer">
  <div id="inner">Click me!</div>
</div>
Enter fullscreen mode Exit fullscreen mode

If you attach event handlers to both the outer and inner elements for a click event, and then click on the inner element, the order of execution will be as follows:

  1. Event Capturing Phase: Event handlers attached to the outer element are executed (if any), starting from the topmost ancestor and moving inward toward the target element.

  2. Event Target Phase: The event handler attached to the inner element is executed.

  3. Event Bubbling Phase:

  • The event handler attached to the inner element is executed (again).

  • Event handlers attached to the outer element are executed (if any), starting from the target element and moving upward toward the topmost ancestor.

By default, events in JavaScript follow the event bubbling mechanism. However, you can explicitly enable event capturing by setting the capture option to true when adding an event listener using the addEventListener() method. For example:

element.addEventListener('click', handler, true);

In the above code, the event handler will be executed during the event capturing phase.

Both event capturing and event bubbling are useful in different scenarios, depending on the desired behavior and event handling requirements.

If you found this helpful please give a like, follow for more posts.
Thanks for your time.

Top comments (0)