views:

28

answers:

2

I would like different nested onmousedown events. For example, consider the following code:

<div id="parent" onmousedown="foo();">
  <div id="child1"> </div>
  <div id="child2"> </div>
  <div id="child3" onmousedown="bar();"> </div>
</div>

I'd like it so that clicking on any area that's inside the parent div, including child1 and child2, would result in foo() being called, and if child3 is clicked then bar() should be called instead.

My attempts so far have shown that the example above would call foo() when child3 is clicked, which isn't what I want.

+1  A: 

In your HTML:

<div id="parent" onmousedown="foo();">
  <div id="child1"> </div>
  <div id="child2"> </div>
  <div id="child3" onmousedown="bar(event);"> </div>
</div>

In javascript

function bar(event)
{
    // usual bar stuff
    event.stopPropagation();
}
Gunjan
Thanks! I'm guessing that this is cross-browser compatible?
Nicolas Wu
No, it isn't. Won't work in IE.
Tim Down
+1  A: 
<script type="text/javascript">

function bar(evt) {
  // Your stuff here
  if (typeof evt.stopPropagation != "undefined") {
    evt.stopPropagation();
  } else {
    evt.cancelBubble = true;
  }
}

</script>

<div id="parent" onmousedown="foo();">
  <div id="child1"> </div>
  <div id="child2"> </div>
  <div id="child3" onmousedown="bar(event);"> </div>
</div>
Tim Down