views:

414

answers:

2

If I have a popup (using a div), how can I have the div to go back to the hidden state when someone clicks anywhere outside of the div?

i.e. the popup is visible, then someone clicks outside the popup, the div should be hidden again.

How can I achieve this functionality?

+3  A: 

A popular way to do this is with an overlay. When your create your div popup, also create a <div id="overlay"> immediately beneath it that takes up the whole screen:

div#overlay{
  position:fixed;
  left:0;
  right:0;
  top:0;
  bottom:0;
}

Optionally, you can use this overlay to darken all other content with, for example, background:#000 and opacity:0.5.

After you've crafted your JavaScript to add this overlay right beneath your popup, add a click listener to it. When the user clicks the overlay, you'll know that s/he has clicked outside of your popup.

Note that position:fixed doesn't work in older browsers. One workaround is, when the overlay is visible, to instead set the overlay to position:absolute, then temporarily add overflow:hidden to <body> to prevent the user from scrolling down.

Ron DeVera
ahh, ok so that's how people do it. basically when yoru popup is visible, add the attributes to the outer div (overlay) to make it greyish, attach the click event to it..bingo! thanks
+3  A: 

A different way of doing it that seems more straight forward to me, is this:

$("body").click(function (event) {
    var outside = $(event.originalTarget).parents("#popup").length === 0;
    if (outside) {
        $("#popup").remove();
        $("body").unbind("click");
    }
});

In short, the originalTarget is what was actually clicked, and the script then checks if #popup is one of its ancestors (called parents in jQuery). If it isn't, the click was outside, and we remove the popup.

Magnar