1

I have a div with a button inside, i want to create separate click events for both but when the button is clicked it is firing the button event and the container event. Can someone help me out. I'm not using jQuery.

var button = document.querySelector('button');
button.addEventListener('click', function(){
  alert('button clicked');
})
var container = document.querySelector('.container');
container.addEventListener('click', function(){
  alert('container clicked');
})
.container{
  width:300px;
  height:300px;
  border:1px solid;
  position:relative;
  z-index:1;
}
button{
  position:absolute;
  top:50%;
  left:50%;
  transform: translate(-50%,-50%);
      z-index:2;
}
<div class="container">
  <button>click</button>
</div>
user3486427
  • 434
  • 9
  • 18

2 Answers2

3

Use e.stopPropagation(); to stop the propagation of event from child element to parent element.

var button = document.querySelector('button');
button.addEventListener('click', function(e){
  e.stopPropagation();
  alert('button clicked');
})
var container = document.querySelector('.container');
container.addEventListener('click', function(){
  alert('container clicked');
})
.container{
  width:300px;
  height:300px;
  border:1px solid;
  position:relative;
  z-index:1;
}
button{
  position:absolute;
  top:50%;
  left:50%;
  transform: translate(-50%,-50%);
      z-index:2;
}
<div class="container">
  <button>click</button>
</div>

Just be sure on stopPropagation and preventDefault

stopPropagation stops the event from bubbling up the event chain.

preventDefault prevents the default action the browser makes on that event.

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

Try e.stopPropagation() on button click from bubbling up the event to the parent.

For More: stopPropagation()

Working Code:

var button = document.querySelector('button');
button.addEventListener('click', function(e){
  e.stopPropagation();
  alert('button clicked');
})
var container = document.querySelector('.container');
container.addEventListener('click', function(){
  alert('container clicked');
})
.container{
  width:300px;
  height:300px;
  border:1px solid;
  position:relative;
  z-index:1;
}
button{
  position:absolute;
  top:50%;
  left:50%;
  transform: translate(-50%,-50%);
      z-index:2;
}
<div class="container">
  <button>click</button>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59