4

http://jsfiddle.net/mnbayazit/by3zy/2/

I want the popup to disappear when I click somewhere on the background. Problem is, it disappears when I click an [X] or the popup itself.

Imagine it being a calendar-picker if that makes my intentions more clear.

How can I get it to do that?

mpen
  • 272,448
  • 266
  • 850
  • 1,236

2 Answers2

8
  1. Set a click handler for the body to remove your popup.

  2. Set a click handler for the popup itself that calls stopPropagation() on the event, to prevent it from bubbling up to the body.

Roughly:

function showMyPopup(){
  ...
  $(myPopupDiv).click(function(e){
    e.stopPropagation();
  });
}
function closeMyPopup(){
  ...
}
$(document.body).click(closeMyPopup);
Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • Ah.. so simple! Was fighting with this for hours at work today, trying to check which element I was clicking on to determine whether or not it should close. http://jsfiddle.net/mnbayazit/by3zy/9/ – mpen Feb 22 '11 at 02:33
0

The basic jist with this technique is to have a wrapping (or independent element layered with z-index) that 'captures' the click event, and hides the elements you desire. I've updated your fiddle with an example of how this would work, except imagine that the blanket element would have a height and width of 100% (to cover the entire viewport).

Nathan Anderson
  • 6,768
  • 26
  • 29
  • Would have been nice if you pasted a link. "Update" creates a new revision #, don't know which you're referring to. – mpen Feb 22 '11 at 02:31
  • Sorry, I didn't know that about jsfiddle. Here's the URL: http://jsfiddle.net/by3zy/5/ – Nathan Anderson Feb 22 '11 at 13:53
  • Err...your blanket solution doesn't display correctly and it doesn't seem like a very good approach. – mpen Feb 25 '11 at 19:38