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?
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?
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>
Use event.stopPropagation();
Like this
document.getElementById("#seconddiv").addEventListener("click", function($event){
$event.stopPropagation();
});
Use event.stopPropagation:
document.getElementById('inner').addEventListener('click', function (event){
event.stopPropagation();
console.log ('Inner div clicked!');
});