ng-click on parent clicks through children

JavascriptHtmlCssAngularjs

Javascript Problem Overview


I have a <div> element which has another <div> element as its child.

I added the ng-click directive to the parent, and expected it not to be fired when clicking the child. However, it does.

<div class="outer" ng-click="toggle()">
    <div class="inner">You can click through me</div>
</div>

Why is it doing this, and how can I avoid it?

Here's a JSFiddle demonstrating the issue

Javascript Solutions


Solution 1 - Javascript

You have to cancel event propagation, so the click event of the parent element won't get called. Try:

<div class="outer" ng-click="toggle()">
    <div class="inner" ng-click="$event.stopPropagation()">You can click through me</div>
</div>

When you click the child element, its event gets triggered. But it doesn't stop there. First the click event of the child element is triggered, then the click event of the parent element gets triggered and so on. That's called event propagation, To stop event propagation (triggering of the parents click events), you have to use the above function, stopPropagation.


Working example

I added some CSS padding, so the example is clearer. Without padding the child element takes up the whole inner space and you can not click on the parent without clicking on the child.

Solution 2 - Javascript

If you want to set different functions for the parent and the child, you can send $event as a parameter for the child function and stopPropagation inside of it. Like this:

<div class="outer" ng-click="onParentClick()">
    <div class="inner" ng-click="onChildClick($event)">You can click through me</div>
</div>

and in your controller:

function onChildClick(event){
    event.stopPropagation();
    //do stuff here...
}
function onParentClick(){
    //do stuff here..
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaehView Question on Stackoverflow
Solution 1 - JavascriptZiga PetekView Answer on Stackoverflow
Solution 2 - JavascriptFelipe RugaiView Answer on Stackoverflow