2
votes

Parent Div Click Function gets called when Child Div Click is clicked. How to overcome this issue

I am using ASP.Net with C#

<div onclick="callme();">
    <a href='#' onclick="Callme2();">Hi</a>
</div>

When I click on anchor tag the div elements onclick also gets executed. How to overcome this ?

3

3 Answers

9
votes

That, of course, depends on the browser.

In newer browsers, call

event.stopPropagation();

on the event object.

In older IE, set

window.event.cancelBubble = true

Read abot the details at Quirks mode.

6
votes

This is due to event bubbling.

<div onclick="callme();">
    <a href='#' onclick="return Callme2();">Hi</a>
</div>

make sure Callme2() returns false to stop the event from bubbling up.

0
votes

I tested it out and it seems the inner event fires first. So the inner event could set some kind of flag. Then the outer event looks at that flag: If it is set, the outer event clears it and returns. If not, it does whatever it normally does. Not as fancy as the other answers that have been posted, but I think it would work and should be browser independent, provided all browsers fire the inner event first (which I would guess they do based on the "bubbling" discussion posted here)