Event Bubbling in JavaScript

The Event bubbling is most used term in JavaScript. Event Bubbling is the term which people must come across while developing a web application or web page using JavaScript.

In this post we are going to understand what is event bubbling and how we can handle it for nested elements.

Let’s start with an example

div {
padding: 50px;
background-color: rgba(150, 150, 150, 0.5);
text-align: center;
cursor: pointer;

In the above code, click handler is assigned to each element.
When we click on input it calls handler for input -> childDiv -> parentDiv
and shows alert
input -> I am from input
childDiv -> I am from child div
parentDiv -> I am from parent div

Don’t you think it’s a bit weird ?

Here is a concept of Event bubbling in JavaScript.

When an event triggers on an element it first calls handler for itself, then its parent and then all the way up on other ancestors(all the following parents in upward chain).

The process is called “bubbling”, because event “bubbles” from the inner element up through parents like a bubble in the water.

Note: that not all the events bubble till DOM. Events like focus, blur, load and some more don’t bubble up

Stop Bubbling

A bubbling event goes from the target element to straight up. Normally it goes upwards till <html>, and then to document object, and some events even reach window, calling all handlers on the path.

But any handler may decide that the event has been fully processed and stop the bubbling.

The method for it is event.stopPropagation().

For instance, here form.onclick doesn’t work if you click on <button>:

<form onclick=”alert('I will not be visible')”>
<button onclick=”event.stopPropagation()”>Click me</button>

stopPropagation() prevents further propagation of the current event. It does not prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method.

If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. If stopImmediatePropagation() is invoked during one such call, no remaining listeners will be called.

The stopImmediatePropagation() method of the Event interface prevents other listeners of the same event from being called.

I hope you understand the concept. Comment me below if you have any questions.

Thanks for reading…!!