Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent click event from outer div if inner div is clicked

I have 2 divs with a js click event. One div is located in the other one.

But I dont want the outer div's click event to be triggered if I click the inner one. How can I prevent that?

like image 493
dunnohowishouldnamemyself Avatar asked Sep 07 '25 10:09

dunnohowishouldnamemyself


1 Answers

By default, event handling starts at the lowest level of the DOM where you have defined a handler to handle the target event. Assuming you have defined event listeners higher in the parent chain to handle the same event, you will need to stop the propagation of the event if you do not wish for the event to be handled beyond the layer you intend for it to be handled in:

e.stopPropagation();

See what happens when you remove that line in the example below:

document.querySelector('.inner').addEventListener('click', function(e) {
  alert('inner div clicked!');
  e.stopPropagation();
});

document.querySelector('.outer').addEventListener('click', function() {
  alert('outer div clicked!');
});
.outer {
  width: 200px;
  height: 200px;
  background: blue;
}

.inner {
  width: 100px;
  height: 100px;
  background: green;
}
<div class='outer'>
  Outer
  <div class='inner'>
    Inner
  </div>
</div>
like image 86
timolawl Avatar answered Sep 10 '25 03:09

timolawl