Ajax Bestiary: A Javascript Field Guide
 
Ajax Bestiary: A Javascript Field Guide
 
 

Handling Nested Clicks With jQuery.

Posted by Don Albrecht

Alright, 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.


5 Comments

Leave a Reply