Event Bubbling and Capturing in JavaScript

Event Bubbling:

In the event bubbling, an event starts at the most specific element and then flows upward toward the least specific element.

For better understanding let’s take an example:-Suppose we have created a div inside the body tag and then we create a button inside that div.

Let’s add the “Click” function on the button, div, and the body.

After clicking the button we will get the following order of events being called.

This means that the flow of function is upward in the case of bubbling.

Now let’s consider the Capturing Case.

Event Capturing:

Event Capturing is opposite to event bubbling, wherein event capturing, an event moves from the outermost element to the target. Event Capturing is also known as Event trickling.

For better understanding lets take the same example which we have taken above:-

To study the concept of Event Capturing we have to change the use of capture flags to ‘true’ as shown below:

Now let’s click on the button and check the order of events occurring.

As you can clearly see that now the order of events is reversed. So this is how event Capturing works i.e down the hierarchy.

How to Stop The Propagation?

To add a propagation barrier we have to use “e.stopPropagation()” within our event. For better instance have a look at the following code.

Now if we click on the button, our propagation will end on the div.

We can restrict our propagation wherever we want using stopPropagation().

Leave a Reply