Recently I’ve needed to handle clicks in jQuery which occur anywhere inside a page but outside a specified area. I’ve been working on a drop down list control which contains a list of checkboxes. The list of checkboxes is shown and hidden by clicking the preceding h4 title, mimicing the functionality of an ordinary drop down list. I wanted to extend this functionality to hide the list when the user clicked anywhere outside the containing div. Here’s the markup for my control:
<div class="ddcontainer">
<h4>My List Title</h4>
<ol>
<li>My List Items</li>
...
</ol>
</div>
The solution was to add a click handler to the root element, the document object, which hides the list.
$(document).click(function(){
$(".ddcontainer > ol").hide();
});
This works because click events on all objects are propagated back up the tree to the document root. This means that even clicks within our list would cause the above code to be called. So to stop valid clicks within our list (i.e. users clicking checkboxes) being passed back up to the document we catch them and stop their propagation:
$(".ddcontainer").click(function(e){
e.stopPropagation();
});
Nice! The only thing that doesn’t work is the link back to the main article.
Nice & simple ! Thanks for the tip.
Thx
its very interesting and useful
Hmm just one con to this is that the right click / middle click close it.
Otherwise its very simple, small and does the job
paul says:
Uhhhh, cool! Thx for this hint. Very nice solution.