Bubbling in JavaScript?

What is bubbling ?

lets suppose there is three boxes One, two ,three. Two is children of one and three is children of two and grandchildren of three like below pen.

HTML


<div class="one">
  <div class="two">
    <div class="three"></div>
  </div>
</div><button>Clicke Me!</button>

CSS

html {
  box-sizing: border-box;
}

*, *::before, *::after {
  box-sizing: border-box;
}

div {
  width: 100%;
  padding: 100px;
}

.one {
  background: thistle;
}
.one .two {
  background: mistyrose;
}
.one .two .three {
  background: coral;
}

Javascript

and Each box had a click event where it logs the classname when it get click.



const divs = document.querySelectorAll('div');

function logs(e){

  console.log(this.classList.value);
  //e.stopPropagation();

}

divs.forEach(div=>div.addEventListener('click',logs,{
  capture: false,
  once: true
}))

document.querySelector('.one').addEventListener('click',()=>{
  console.log("One clicked!")
})

document.querySelector('button').addEventListener('click',()=>{
  console.log("clicked!")
},{
  once: true
})

Now when we click inside of box three it will trigger associated event and also associated event of box one and box two as well. why ? Because box three is inside two and two inside one. This is called Bubbling event.

To See that open console and clicked inside box three you will see the output


three
two
one
One Clicked

to Stop triggering parent event you should add e.stopPropagating () inside your child log function(event listener callback). It will not trigger parents event . Like the below one.

function logs(e){

  console.log(this.classList.value);
  e.stopPropagation();

}

For More Information - JavaScript Event Capture, Propagation and Bubbling By Wesbos.

Any suggestion and correction please let me know.

Thanks for reading.