views:

261

answers:

3

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 ?

+5  A: 

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.

Tomalak
+9  A: 

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.

gnud
A: 

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)

MatrixFrog
Yeah, that's way too convoluted. Just stop the event propagation, which is the "proper" way to do it.
Tyson