Handling Nested Clicks With jQuery.
November 27th, 2007Alright, so here’s the problem. I need to apply the ability to select any div inside an ajax app. Including divs nested inside other nestable divs. ex.
<div id="outer" class="clickable">
<div id="inner" class="clickable"></div>
</div>
In jQuery, if I simply call $('.clickable').click(...); I wind up with a click event that fires twice when inner is clicked. Once with target inner and once with target outer. Since I only care about the inner most div selected, I need some way to ignore the click event on the outer div.
I achieve this by assigning an attribute to the currently selected div. In the case of my most recent project, I was able to piggyback on a class change, but any attribute would do.
Step 1: Determine if this is the innermost selected div
There are two possible scenarios for any target div. It is either the innermost clicked div or it isn’t. If it isn’t the innermost div it will either already have a child div with a set “selected” attribute or it won’t. If it has a selected child div, we escape.
if ($(target).find(".selected").size() ) { return; }Otherwise, we remove all elements with set selected attributes and set the selected attribute for the target div.
$('.selected').removeClass( "selected");
$(target).addClass( "selected" );Note: If the containing div was the first processed, we don’t have a problem because we will clean up the current selection when the function is called on the innermost div.
The system is working like a charm for me in my current project. If anyone knows a more efficient way to do it, please share it in the comments below.


Previous Post
Next Post

5 Comments
November 28th, 2007 at 8:40 am
I think you only need to prevent propagation of the event:
event.stopPropagation(); // W3C
event.cancelBubble = true; // IE
November 28th, 2007 at 8:41 am
Sorry, forget that. I was thinking in events not in calling click method
November 28th, 2007 at 9:12 am
You can break the click chain by simply returning false from the method to stop the bubbling as well. Since the Standard calls for all events to propagate to their ancestor, this offers a simpler approach.
November 28th, 2007 at 9:38 am
return false only stops bubbling. It doesn’t deal well with the situation where both objects in the stack have click handlers.
November 28th, 2007 at 11:13 am
[...] I posted instructions for handling a series of nested clicks with jquery. Today I’m going to follow up that post with a more sophisticated solution to handle a corner [...]