Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Event Bubbling?
2.1.
Syntax
2.2.
Parameter
3.
Example of Event Bubbling
3.1.
HTML Code
3.2.
HTML
3.3.
CSS Code
3.4.
CSS
3.5.
Javascript Code
3.6.
Javascript
4.
Stop Event Bubbling
4.1.
stopPropagation() Method
4.2.
stopImmediatePropagation() Method
5.
Frequently Asked Questions
5.1.
What is event capturing?
5.2.
How to bubble up an event in JavaScript?
5.3.
What is the difference between Event Bubbling and propagation?
5.4.
What is the difference between Event Bubbling and event capturing?
5.5.
What is event capturing in Javascript?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Event Bubbling in JavaScript

Author Sohail Ali
1 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

An event in Javascript is an action or occurrence that happens in the browser. It is often a result of user interaction or other system triggers. Events can be anything from a mouse click, keyboard press, or window resize. It can also be more complex interactions, such as form submissions, element focus changes, or data loading.

Event Bubbling in Javascript

In this blog, we will see what events are and what is bubbling in Javascript. So tighten your seatbelts, and let's start learning.

What is Event Bubbling?

In JavaScript, event bubbling is a mechanism that determines the order in which event handlers are executed when an event is triggered on an HTML element that is nested within other elements. When an event occurs on a deeply nested element, such as a button inside a div inside a section, it can "bubble up" through the ancestor elements in the HTML hierarchy, triggering event handlers on each ancestor element in turn.

Note: Events have the default nature of bubbling up, but you can stop this as well. Also, you can detect whether an event bubbles up all the way through the DOM or not using the ‘bubbles’ property. 

Syntax

addEventListener (type, listener, useCapture)

Parameter

  • type: It refers to the type of event 
     
  • listener: It is the function that we want to call whenever an event of a particular type occurs.
     
  • userCapture: It is a boolean value. By default, it is false, indicating it is in the bubbling phase. If it is true it means no bubbling phase right now.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example of Event Bubbling

Now let's learn event bubbling in Javascript with the help of an example.

HTML Code

  • HTML

HTML

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!-- Outer div starts here -->
<div id="Outer_div">

<h3> Outer Div</h3>
<!-- Inner div starts here -->
<div id="Inner_div">
<h3> Inner Div</h6>
</div>

</div>
<script type="text/javascript" src="Event.js"></script>

</body>
</html>

CSS Code

  • CSS

CSS

#Outer_div{
margin: 60px;
padding: 60px;
width: 250px;
height: 250px;
background-color: blue;
box-sizing: border-box;
}

#Inner_div{
width: 125px;
height: 125px;
background-color: yellow;
}

Javascript Code

  • Javascript

Javascript

// Creating a variable for inner div
var inner_div = document.getElementById('Inner_div') ;
inner_div.addEventListener('click', function() {
// Displaying the message
console.log('Pressed Inner Div');
});

// Creating a variable for outer div
var outer_div = document.getElementById('Outer_div') ;
outer_div.addEventListener('click', function(){
// Displaying the message
console.log('Pressed Outer Div');
});


Output

Even bubbling output

Explanation

In the above example, we created two div elements using HTML. The smaller/inner div element is a child element of the bigger/outer div element. After this nesting, we added CSS and Javascript to the code. In Javascript code, we got the elements by using their id using the getElementById() method. After that, we called the event listener on both div elements and if the user clicks the div element anywhere, we will get a print statement respectively.

Now, whenever we click the outer div number of times, we will get a print statement for the outer div that many times repeatedly.

Outer div output

But, whenever we click on the inner div, the event is also automatically propagated/transferred to the outer div. This will trigger the outer div. Thus, we will also get a print statement for the outer div whenever we click the inner div.

Inner div output

Let us understand the flow of the program using a flow chart:

flowchart

As we can see from the flow chart, the events follow a hierarchical path. Whenever an event initiates from an element, it propagates that event to its parent elements.

This phenomenon is nothing but an event bubbling in Javascript. Almost all browsers support event bubbling by default. But what if we want an event to run only on a single element and not propagate to the top? To stop event bubbling, we can use the few approaches below.

Stop Event Bubbling

Below are some methods using which we can stop event bubbling in Javascript.

  • stopPropation() method
     
  • stopImmediatePropagation() method
     

Let’s now look at these methods and learn how they work.

stopPropagation() Method

This method is used whenever we want to stop event propagation from the child element to the parent element.

Syntax

event.stopPropagation();


Example:

In order to stop the event bubbling in Javascript, we can write the above method in Javascript code for inner div, for example: 

var inner_div = document.getElementById('Inner_div');
inner_div.addEventListener('click', function(){
	console.log('Pressed Inner Div');

	// This will stop event bubbling
	event.stopPropagation();
});


Note: The rest of the HTML and CSS code remains the same.

After making this change in our code, we will get the following output whenever we click the inner div multiple times.

stopPropagation output

It is important to note that this method only invokes the event handler of the target element. Thus this method could successfully stop the process of event bubbling in Javascript.

Note: It is recommended not to use this method often because it may create unexpected problems later.

stopImmediatePropagation() Method

This is another method using which we can stop event bubbling in Javascript. In DOM, multiple handlers may exist for a single event that may be independent of each other. So using this method, we can stop not only the further propagation of events but also some other event handler of the same event. 

Syntax

event.stopImmediatePropagation();


Example:

Let's use this method in our Javascript code and see the result.

We need to make the following changes in our inner div code.

var inner_div = document.getElementById('Inner_div') ;
inner_div.addEventListener('click', function(){
	console.log('Pressed Inner Div');
	event.stopImmediatePropagation();
});


Output

stopImmediatePropagation output

Note: The rest of the HTML and CSS code remains the same.

Wooh! Finally, we are able to stop event bubbling in Javascript completely.

Frequently Asked Questions

What is event capturing?

Event capturing is the phase where events move from the root to the target element in the DOM hierarchy before the actual event reaches its target.

How to bubble up an event in JavaScript?

You don't need to explicitly bubble up an event in JavaScript; it naturally occurs when an event triggers on a nested element, moving up through its ancestor elements in the DOM hierarchy.

What is the difference between Event Bubbling and propagation?

Event Bubbling is the phase where an event moves up from the target element to the root of the DOM hierarchy. Event Propagation encompasses both capturing (downward) and bubbling (upward) phases.

What is the difference between Event Bubbling and event capturing?

Event Bubbling moves events up from the target to the root of the DOM hierarchy. Event Capturing moves events down from the root to the target. Both are phases of event propagation in the DOM.

What is event capturing in Javascript?

Event capturing involves events moving from the outermost to the target element. This contrasts with event bubbling, where events spread from target to outer elements. Capturing precedes bubbling in sequence.

Conclusion

This article discusses the event bubbling in Javascript, along with an example. We also discussed different methods which are used to stop event bubbling in Javascript. We hope this blog has helped you enhance your knowledge of event bubbling in Javascript. If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your coding ability, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Live masterclass