Event Bubbling in JavaScript

Event Bubbling in JavaScript

Event Bubbling and Event Capturing is one of the important concepts in JavaScript as well as the most commonly asked javascript interview question.

But before going into it we must know, What is an Event?

Events in Javascript ✨

In javaScript events are basically an interaction between the user and the HTML web page. When a user clicks on a button or presses a key on the keyboard and the mouse scrolls etc. an event occurs.

The sequence or an order in which the events are received on the webpage is known as Event-flow. So, the process of event flow depends on the three parts Event Capturing, Event Targeting, and Event Bubbling.

In this blog, we will learn what is Event Bubbling in JavaScript?

Event Bubbling 💭

Event bubbling is a common concept that you will encounter while developing a web application.
When there are nested elements and each element has registered an event, and if we click on the inner element, then it will call the inner function and outer function as well. This is known as Event bubbling. It just bubbles up.

Let's understand with a code sample: bubbling-1.png

Here we have added three nested div and gave them names as

Grandparent(in Green color), Parent(in Blue color), and Child(in Yellow color) and registered a click event which will console the name of that element.

Here's a code snippet:

HTML

html1.png

Javascript

js1.png

In the above ex code snippet, we can say that clicking on the child div should only console child as an output, but it prints

child
parent 
grandparent

Here the concept of Event bubbling comes into the picture. Even though we are not clicking on the outer div which is grandparent and parent, we are receiving outputs.

This is happening because the child div lies inside the parent div as well as the grandparent div. So, when we click on child div, we indirectly click on both the grandparent and parent div and that's how the propagation is moving from inner div to outer div., or we can say events are just bubbling up.

This process of propagating from inner elements to outer elements in the Document Object Model(DOM) is called Event Bubbling.

Hope now have got a basic understanding of Event Bubbling. 🎉