In this tutorial, we will learn How Event Bubbling works in javascript with example

Event Bubbling:

  • Event bubbling refers to the propagation of an event from the innermost element, where the event occurs, to the outermost element.
  • event “bubbles up” the DOM tree.
  • This means that if you have a nested element inside another element and an event occurs on the inner element, both the inner and outer elements will receive the event.

Example:

Consider the following HTML:

In this example, we have a button inside a p element which is inside a div element. When we click the button, we want to log the ID of the element that received the event.

<div id="div1">
  <p id="p1">
    <button id="button1">Click me</button>
  </p>
</div>
//Javascript
document.getElementById("button1").addEventListener("click", function(event) {
  console.log("Button clicked");
});

document.getElementById("p1").addEventListener("click", function(event) {
  console.log("Paragraph clicked");
});

document.getElementById("div1").addEventListener("click", function(event) {
  console.log("Div clicked");
});

When we click the button, the following will be logged to the console:

Button clicked
Paragraph clicked
Div clicked

This shows that the event started at the button, then bubbled up to the paragraph, and finally the div. This is why it’s called event bubbling.

You can stop the event from bubbling up to the higher-level elements by calling event.stopPropagation() in the event handler.

Thanks for Readding

Comments are closed.