...

View Full Version : How do you make onlick fire for ONLY the "top-most" div?



BMAN99
07-14-2012, 03:29 AM
Hey guys,

Let's say I've got 2 divs, A and B, and each div has a separate onclick event. Div "A" is in the background, and div "B" is in the foreground, like this...

_______________________________________
|............................................................|
|........................Div A.............................|
|............................................................|
|..............___________________................|
|..............|............................|...............|
|..............|......... Div B............|...............|
|..............|__________________|...............|
|............................................................|
|............................................................|
|______________________________________|


What I want to do, is when div B is clicked on, it fires ONLY the onclick event for div B. But as it is, whenever I click on Div B, it fires the onclick event for Div B AND Div A.

So... how can I keep the div A onclick event from firing whenever I click on Div B?

DrDOS
07-14-2012, 04:06 AM
I think the correct answer is to give both divs a z-index, and give div-b a higher one. Can I put my hand down now?

xelawho
07-14-2012, 04:34 AM
the problem, I believe, is called event propagation (http://javascriptexample.net/events03.php)... or bubbling... and CSS won't help you there. Have a look at the link and the code to stop it

vwphillips
07-14-2012, 09:50 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
</head>

<body>
<div style="position:relative;width:400px;height:400px;background-Color:red;" onclick="Test(1);" >
<div style="position:relative;left:100px;top:100px;width:200px;height:200px;background-Color:blue;" onclick="Test(2);" ></div>

</div>
<script type="text/javascript">
/*<![CDATA[*/
function Test(nu){
var e=window.event||arguments.callee.caller.arguments[0]
e.cancelBubble=true;
if (e.stopPropagation){
e.stopPropagation();
}
alert(nu);
}



/*]]>*/
</script></body>

</html>

BMAN99
07-14-2012, 04:36 PM
Vic,

Thank you so much... that's perfect! :)

And xelawho, thanks for the link... very informative!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum