# Usage of stopping event bubbling in JavaScript

Let inside one parent we have a button and some block:

`<div id="parent"> <button>click me</button> <div id="block"> text </div> </div>`

Get references to our elements into variables:

`let parent = document.querySelector('#parent'); let button = document.querySelector('button'); let block = document.querySelector('#block');`

Let our block be initially hidden:

`#block:not(.active) { display: none; }`

Let's make it so that by clicking on the button our block appears:

`button.addEventListener('click', function() { block.classList.add('active'); });`

And now we will make it so that by clicking on any place of the parent, our block is hidden:

`parent.addEventListener('click', function() { block.classList.remove('active'); });`

However, we are in for an unexpected surprise: since the button is inside the parent, then clicking on the button simultaneously means also clicking on the parent. This means that at first our block will appear, and then, due to the bubbling of the event, the handler in the parent will work and our block will be hidden.

This is where the ability to cancel the bubbling comes in handy: we can make it so that when you click on the button to cancel the bubbling, the parent does not react to this click.

Implement the correct performance of the described task on your own.

← →
↑
en ru