Event Bubbling and Capturing in JavaScript

Event Bubbling and Capturing in JavaScript

What are events?

Events are any kind of actions in JavaScript. They can either be user initiated(like a button click) or system initiated (like document load). When these events occur, a lot goes on in the back end which is most of the times not visible to us. You can have handlers attached to these events which will do a particular task when an event occurs. Example of an event can be a click event and a click handler can be attached to it, that will perform a set of tasks that you want it to, when a target is clicked.

Phases of events in JavaScript

When an event occurs, it goes through the following phases in the given order:

  1. Capturing Phase
  2. Target Phase
  3. Bubbling Phase

Let us take a look at each one to understand it better

Capturing phase in JavaScript

This is the phase that is triggered at the very beginning when an event like a button click occurs. This travels from top to bottom of your DOM tree until it reaches the target.

Consider the following html.

<body id='container'>
  
<div>
    <a>Click me!</a>
  </div>

</body>

When we attach click handlers in capturing phase to each of the elements of the DOM tree and then say we click on the anchor tag. The capturing phase is triggered first and the trigger takes place from top to bottom direction until the target that is the anchor tag is clicked.

Target Phase in JavaScript

This is the phase which follows the capturing phase and is triggered when the capturing reaches the target. The target in the above example is the anchor tag. So this phase will come into play when the capturing travels from the html down the DOM tree and reaches the anchor tag.

Bubbling Phase in Javascript

This is the phase in which most of the time we register our handlers. This is by default the phase of event handling.

Once the target phase is executed, the execution enters into the bubbling phase. Unlike the capturing phase, this travels from bottom to top of the DOM tree. It initiates from the target which is anchor in our case. It travels from the anchor to each of its ancestors triggering the events of each if registered until it reaches the top level DOM node that is HTML in our case.

 

Take a look at the simple example below which illustrates these phase in action:

Comments are closed.