tags:

views:

30

answers:

3

I have several divs that are nested within each other. Each has it's own onclick event. So, imagine that it's like a sandwich, the bottom layer is bread (this layer is geographically larger than the ones that are nested inside),then there's lettuce and then tomato on top.

So, it looks like this:

---------------------------
| Bread                   |
|                         |
| ----------------------- |
| | Lettuce             | |
| |                     | |
| | ------------------- | |
| | |Tomato           | | |
| | |                 | | |
| | |   <*click>      | | |
| | |                 | | |
| | |                 | | |
| | ------------------- | |
| ----------------------- |
---------------------------

Currently, when the user clicks on the tomato, it fires off the proper sequence for the tomato, but then things go awry. Because as soon as it fires tomato, it recursively fires lettuce, and then finally the bread.

I suppose it does this because technically the user DID click within those divs, but only because tomato is nested inside them.

The way it should work is that if the user clicks on the Tomato portion of the sandwich, then it should fire off only tomato's event. On the other hand, if the user clicks on the lettuce portion that is peeking out behind tomato, then it should fire lettuce.

So, my question is whether it is possible to make the divs "opaque" for clicks so that even though they are nested inside each other, only the one that was actually clicked on counts.

+1  A: 

You can add a return false after your current handler code to prevent the click from bubbling up or propagating...this is what causes the click events on the parent elements.

I would suggest the following reading for a better understanding of what's happening: quirksmode.org's excellent explanation of event bubbling.

Nick Craver
A: 

In non-IE browsers event.stopPropagation(); will stop the event from bubbling up to parent nodes, in IE, event.cancelBubble = true; should do the trick. event is the argument passed to the listener.

Andrew Dunn
A: 

Hey guys, thanks for the help. Unfortunately, I think I may have inadvertently left out a vital piece of information. The JS in this case is actually firing an AJAX request back to the server. So, for some reason in this type of situation the "return false" on the event handler didn't work.

I suspect that the XMLHttpRequest call to the server was probably all fired at the same time.

However, I was able to fix the problem by putting a block-level (empty) <a> tag inside the div, and then putting my click event on the <a> tag instead of the <div>.

So I just changed the code from this:

<div class='container' id='idstring' onclick="ajaxcall(parameters)">
  <? server-side call to recursive function ?>
</div>

To this:

<div class='container' id='idstring'><a onclick="ajaxcall(parameters)">
  <? server-side call to recursive function ?>
</a></div>