tags:

views:

42

answers:

3

When the user clicks on a .popup_link, a little popup window is displayed and any other popup windows are removed:

$("a.popup_link").click(function(){
    hide_all_popups()
    make_popup($(this).id)  
});

But I want it to also hide_all_popups() when the user clicks anywhere else on the page thats not the popup. I need something like this:

$("[ANY]:not(a.popup_link)").click(function(){
    hide_all_popups()
});

How do I do this?

+2  A: 

Bind your 'hide' handler to a document and don't allow event to bubble in your 'show' handler'.

thorn
+3  A: 
$(document).click(hide_all_popups);

$("a.popup_link").click(function(){
    hide_all_popups()
    make_popup($(this).id);
    return false; // this line is very important it tells the event (click) to not go further (to not go to hide_all_popus)...
});
vvo
`return false` stops the browser from handling the event. I think it should be `event.stopPropagation()` the one to stop the click event to propagate on child elements.
Alex Bagnolini
From jquery doc : "To stop both default action and event bubbling, your handler has to return false" http://docs.jquery.com/Events/bind
vvo
+1, good to know :)
Alex Bagnolini
It's better the bind the mousedown event to the document and then you can use the click event below the document level and stop the event bubbling. Here is a great tutorial by Ben Nadel http://www.bennadel.com/blog/1754-Track-Document-Level-Clicks-With-jQuery-MouseDown-Events.htm
Nick Lowman
+1  A: 

There's a really good tutorial here by Ben Nadel which addresses the issue you have. The idea to bind the mousedown event to the document element rather than using the onclick. I'll let you read the tutorial as it was very helpful for me when I had the same issue.

$(document).bind('mousedown', function() {
            //hide all popups
        });

http://www.bennadel.com/blog/1754-Track-Document-Level-Clicks-With-jQuery-MouseDown-Events.htm

Nick Lowman
Ben Nadel got the idea from the jQuery UI team with their date picker widget so I guess it's way to do things.
Nick Lowman