Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  74] [ 2]  / answers: 1 / hits: 35035  / 10 Years ago, sun, january 18, 2015, 12:00:00

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


More From » html

 Answers
13

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.


[#68172] Thursday, January 15, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gregorio

Total Points: 362
Total Questions: 95
Total Answers: 93

Location: Puerto Rico
Member since Sun, Jun 27, 2021
3 Years ago
gregorio questions
Fri, Apr 8, 22, 00:00, 2 Years ago
Mon, Sep 6, 21, 00:00, 3 Years ago
Sun, Sep 13, 20, 00:00, 4 Years ago
;