Rob Bell

Handling clicks outside a specified area in jQuery

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();
});

Published

28 February 2009

Category

Articles

10 comments

Paul says:

Uhhhh, cool! Thx for this hint. Very nice solution.

Benjamin Reid says:

Nice! The only thing that doesn’t work is the link back to the main article. ;)

Florian Cargoet says:

Nice & simple ! Thanks for the tip.

Rob Bell says:

@Benjamin - Thanks for pointing that out, all working now.

arffak abdallah says:

Thx. It's very interesting and useful :)

Corangar says:

Hmm just one con to this is that the right click / middle click close it. Otherwise its very simple, small and does the job ;)

Rob Bell says:

@Corangar - Thanks for the comment but this is by no means a complete solution. The purpose was to demonstrate click catching, I think adding any additional functionality would complicate the example.

Alexandre says:

Oh man, thanks, this just made my day!

Rohan says:

Thanks man… thanks for the hint….that was a good logic.

Flavio Santana says:

Thanks! Great solution.