Event Bubbling in JavaScript

Event-Bubbling-in-JavaScript-feature-image.jpg

While building interactive websites with the help of JavaScript, it is important to handle JavaScript DOM events like clicking buttons, filling out forms, or submitting data. You need to manage these events efficiently to make sure that your website responds correctly to these actions. Event bubbling in JavaScript is an important concept that helps with event handling. In this blog, let us explore event bubbling in JavaScript, its uses, and how it works in detail.

Table of Contents:

What is Event Bubbling in JavaScript?

Event bubbling in JavaScript means that when an event occurs (like a click) on the child element, that same event comes up and affects its parent element as well. In this way, both the child element and the parent element can respond to the event.

Imagine you have a button inside a <div>, and that <div> is inside another large container. Now, when you click on the button, the click doesn’t only affect the button; it also “bubbles up” and reaches the <div>, and then the container, and so on, until it reaches the main page (document).

This whole process, where the event starts from the clicked element and moves upward towards its parent element, is called event bubbling in JavaScript.

How does Event Bubbling Work?

How does Event Bubbling Work

In order to understand how event bubbling works in JavaScript, have a look at the image above. It shows two elements: a Parent and a Child. When you trigger a JavaScript DOM event on the Child (like clicking a button), the event does not stop here; it bubbles up and reaches the Parent as well.

  • When you click on the Child element, the event gets triggered.
  • After that, the same event bubbles up to the Parent element.
  • If both the Child and the Parent have event listeners, they both will respond to the child at first and then to the parent.

This movement of the event in an upward direction is called event bubbling.

Launch Your Web Development Career
Start Learning Now
quiz-icon

Example of Event Bubbling

Let us explore the example of event propagation, which is used to show the events travel from the clicked elements to their parent elements.

Code:

Html

Output:

event bubbling in JavaScript

Explanation:

The above code is a simple example that shows event bubbling in JavaScript. When you click on the “Click Me” button, the event at first triggers the event listener of the button, which shows “Button Clicked” in an alert. After that, the same event moves up to the inner div by triggering its listener and showing “Inner DIV clicked”. After that, it bubbles up to the outer div, which then shows “Outer DIV clicked”. At last, it reaches the body, where a message is logged in the console, but it does not show any alert. This is a step-by-step bubbling effect that helps you to see how events travel from the clicked element up through its parent elements in the DOM.

Why is Event Bubbling Useful?

Given below are some reasons why event bubbling can be useful:

1. Less code to write: You don’t have to add event listeners to every single element. You can just add one event listener to the parent element, and it will handle events from its child elements as well.

2. Easier to Handle Dynamic Elements: If you are adding elements to the page using JavaScript (like buttons or list items), event bubbling helps you to manage their events without using any extra setup.

3. Better Performance: Having fewer event listeners means that your web page runs faster, especially when you have a lot of elements on the page.

4. Cleaner and Organized Code: Event bubbling also helps to keep your code clean by handling all the similar events in one place instead of repeating the same logic.

How to Stop Event Bubbling?

Sometimes, you don’t want an event to keep moving up to the parent element from the child element. In those cases, you can prevent event bubbling in JavaScript with the help of a simple method called stopPropagation().

How it Works

When an event occurs in JavaScript, it lets it travel up through its parent elements. But if you want it to stop right there, just write event.stopPropagation() inside your event listener. An example code is given below for your reference.

Code:

Javascript

Explanation:

The above JavaScript code adds a click event to a button having the ID myButton. When you click on that button, it shows an alert: “Only the button reacts, and not the parent!”. It then stops the event from going up to the parent elements. Hence, only the button responds here, and the parent elements won’t respond to the click.

Event Bubbling vs Event Capturing

Feature Event Bubbling Event Capturing
Order of Event Flow Starts from the child and moves to the parent. Starts from the parent and moves to the child.
Default Behavior Happens by default in JavaScript. Doesn’t happen unless you enable it manually.
When Listener is Triggered After inner elements (like buttons) respond. Before inner elements get a chance to respond.
How to Use Just add an event listener normally. Add true as the third argument in addEventListener().
Common Usage Most commonly used in real-world code. Rarely used, mostly for specific needs.
Real-Life Example Dropping a stone in water, and the ripples go out. A sound starts from the hall and reaches the room.
Control Over Event Flow Easier to control with stopPropagation(). Less commonly used, so not often controlled.

Best Practices for Using Event Bubbling

  1. Instead of adding event listeners to each child element, add one event listener to the parent. This helps you to save time, reduce code, and improve performance.
  2. You should not block event bubbling unless you have a valid reason. Preventing event bubbling may render other blocks of your program ineffective.
  3. You should write clean and short event functions. This makes it easier for you to understand and debug event bubbling.
  4. To prevent confusion, use the clear names of a function, such as handleClick or handleFormSubmit, when using groups of events. This is because events bubble through multiple layers.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

Event bubbling is an important process in JavaScript that helps you write cleaner, more efficient code for your web applications. It enables you to be smarter in managing events by allowing parent elements to handle actions of their children. When you understand how it functions, when to utilise it, and how to prevent event bubbling, you can create interactive websites with better control and less code. Therefore, you should practice and use event bubbling in JavaScript in your applications; it will be easier and more convenient to develop event handling.

To learn more about events and event bubbling, check out this Web Development course and also explore JavaScript Interview Questions prepared by industry experts.

Event Bubbling in JavaScript – FAQs

1. Can event bubbling happen with other events besides clicks?

Event bubbling can be applied to a lot of events such as mouseover, keydown, submit, and so on.

2. Is event bubbling supported in all browsers?

Yes, event bubbling is supported by default in all major browsers.

3. Can event bubbling slow down my website?

Not in general, but performance can be influenced by the addition of excessive listeners that are not needed.

4. What if I use both event bubbling and capturing together?

Both will run, but capturing runs first, and bubbling happens after.

5. Can I use event bubbling with dynamically created elements?

Yes, that’s one of the best use cases for event bubbling using event delegation.

About the Author

Software Developer | Technical Research Analyst Lead | Full Stack & Cloud Systems

Ayaan Alam is a skilled Software Developer and Technical Research Analyst Lead with 2 years of professional experience in Java, Python, and C++. With expertise in full-stack development, system design, and cloud computing, he consistently delivers high-quality, scalable solutions. Known for producing accurate and insightful technical content, Ayaan contributes valuable knowledge to the developer community.

Full Stack Developer Course Banner