Event Bubbling and Capturing in Javascript

Run your aggregation queries at a speed of 14x without spending $$$
Reading Time: 3 minutes

Introduction

In Javascript, you must have worked with the events. In this blog, we will be going through two important concepts in Javascript related to events i.e. Event bubbling and Event Capturing. Both of these concepts are related to the propagation of events which we call Event Flow.

So, let us understand these concepts.

Bubbling

Event Bubbling is the concept of the sequence of invoking the event handlers where the event handlers are nested in another element. The sequence of events is from the innermost element covering all its ancestors along the way. To understand it better let us see this example:

<!DOCTYPE html>  
<html>  
<head>  
  <meta charset="utf-8">  
  <meta name="viewport" content="width=device-width">  
  <title>Event Bubbling</title>  
</head>  
<body> 
 <div id="parent1">  
    <button id="btn1">Click</button>  
  </div>  
    
  <script>  
    var parent = document.querySelector('#parent1');  
      parent.addEventListener('click', event=> {  
        console.log("calling event of Parent");  
      });  
  
   var child = document.querySelector('#btn1');  
      child.addEventListener('click', event => {  
        console.log("calling event of Child");  
      });  
  </script>  
</body>  
</html> 

Here, we have a simple HTML file in which we have added a button inside a div in the body. We have provided id’s to both of them in order to add an event listener to them. In the script tag, we first query the element with the help of querySelector and store that in a variable. Then on that variable holding the element, we add the event listener on click event.

In the event listener, we are just making simple console statements in order to understand the sequence of invoking the event handlers after clicking on the button. So when we will click on the button and check the console, we can see the console statements. For the above code the output will be as follows:

calling event of Child

calling event of Parent

First, the innermost event is called and then the parent event is called. This is how event bubbling works. It first will call the event listener on the deepest nested element, then on its parent and so on.

Stopping Bubbling

You can also stop this event bubbling with the help of the event handler when the event has been processed completely. That is, if we do not want to run the parent event handlers and run the event handler of the nested element only then we can stop bubbling. For stopping the process of bubbling, we use the event.stopPropagation method.

Here is how we can stop it. In the same HTML file, we can just modify the button event listener like this:

 var child = document.querySelector('#btn1');  
      child.addEventListener('click', event => {  
      event.stopPropagation();
        console.log("calling event of Child");  
      }); 

You can see everything is same in the event handler except for adding the event.stopPropagation method. And now when you click on the button, you will notice that the parent event is not called in this case. So, this is how we can stop it.

Capturing

Event Capturing is the opposite of Event Bubbling. It is the concept of the sequence of invoking the event handlers where the event handlers are nested in another element and the sequence of events is from the outermost element covering all its inner elements coming along the way. Event Capturing is used rarely because event bubbling is more preferable to handle the event flow.

Now, modify the script tag in this way and notice the change in the sequence of events.

 <script>  
    var parent = document.querySelector('#parent1');  
      parent.addEventListener('click', event=> {  
        console.log("calling event of Parent");  
      },true);  
  
   var child = document.querySelector('#btn1');  
      child.addEventListener('click', event => {  
        console.log("calling event of Child");  
      });  
  </script>

Here we have added another argument as true. By default it is false and when you want to turn on event capturing then in that case you need to set it as true and the output will be as follows.

calling event of Parent

calling event of Child

Conclusion

So, we have now learnt what is event bubbling and event capturing in javascript and how we can implement it. Event bubbling is the phase where event handlers are executed from innermost element to top most and the opposite in event capturing.

For more updates, please follow our LinkedIn page- FrontEnd Studio.

Thank you for sticking to the end. If you like the blog, please give a thumbs up and share it. Feel free to share your feedback in the comments.

Written by 

Kiran Jeet Kaur is working as a Software Consultant in Knoldus. Her practice area is Front End. She is always open to learn new things. Her hobbies include watching movies and listening to music.

Leave a Reply