Reputation: 1219
I have similar code like below and I want If I clicked in Child Div then Parent Div click event should not trigger.
<div class="parentDiv" (click)="parentDiv()">
<div class="childDiv" (click)="childDiv()">Child Container</div>
</div>
When I am clicking on "childDiv" so first it triggers "parentDiv()" event and then "childDiv()" event.
Can you please help me to resolve it?
Thankyou in advance
Upvotes: 4
Views: 1781
Reputation: 10262
A bubbling event goes from the target element straight up. Normally it goes upwards till <html>
, and then to document object, and some events even reach window, calling all handlers on the path.
But any handler may decide that the event has been fully processed and stop the bubbling.
The method for it is event.stopPropagation()
.
<div class="parentDiv" (click)="parentDiv()">
<div class="childDiv" (click)="$event.stopPropagation()">Child Container</div>
</div>
DEMO
function parentDiv() {
alert('parent div')
}
div {
cursor: pointer;
}
<div class="parentDiv" onclick="parentDiv()">Parent Div
<div class="childDiv" onclick="event.stopPropagation()">Child Container</div>
</div>
Upvotes: 3
Reputation: 2024
Use event.stopPropagation();
in the function attached to the .childDiv
In Javascript there is something called Event Bubbling; when an event fires for one element it fires for all of it's parent elements as well.
Heres a code snippet displaying the code needed
document.getElementById("parentDiv").addEventListener("click", function (e){
alert('parentDiv clicked');
});
document.getElementById("childDiv").addEventListener("click", function (e){
e.stopPropagation();
alert('childDiv clicked');
});
<div id="parentDiv">
Parent Container
<div id="childDiv">Child Container</div>
</div>
Upvotes: 1
Reputation: 10148
This is where you need event.stopPropagation();
<div class="childDiv" (click)="childDiv(event)">Child Container</div>
And
childDiv(event) {
event.stopPropagation();
}
What happening in your case is called propagation of events.
When you click on child div, the click event propagates to parent div. You need to stop that propagation.
Above is the way to do it.
Or if you want a one line solution this it
<div class="childDiv"
(click)="childDiv(event);$event.stopPropagation()" >Child Container</div>
Upvotes: 4