tags:

views:

36

answers:

2

Hello, I have a Dialog box to all a user to click a project, that opens on click.... Here's the code:

$("#byproject").live("click", function() {
    $("#projectPicker").fadeIn();
    return false;
});
// Close the space dialog on selection
$(".projectSelect").live("click", function() {
    $("#projectPicker").fadeOut('fast');
});

This works very well to open the dialog box that is being position:absolute, next to the "select projects" button...

Problem here is that if the user clicks outside the box (ie they change their mind) the box doesn't close...

Is there some smart way I can say, when this thing is open, if the user clicks anywhere outside of the dialog box, close it?

Thanks

+3  A: 

You need to attach a click event to the document body that will close the window, and prevent propagation of the click event so click on the window will not close it. I wrote a similar answer to a similar question 2 years ago - not sure if it's similar enough to close this one.

$('body').click(function() {
  //Close window
});

$('#projectPicker').click(function(event){
    event.stopPropagation();
});

By the way, is there a reason you are using a live event on the links? at least the one with the id should probably use a regular click event.

Eran Galperin
Because you are not using jquery ui or anything that will pop up with a background this will probably be the easiest thing.
Matt
thanks but how do I enable this bind when the dialog I made is open? I don't want this bind always running? any idea how jquery ui dialog does it? Id love to use jquery ui dialog but I need absolute positioning.
TheExit
You can add the click event on the body when the dialog opens and remove it using .unbind('click',...)
Eran Galperin
A: 

I think this should suffice

$('*').click(function(e){
        e.stopPropagation();
        if($(this).is('#byproject')){       
             $("#projectPicker").fadeIn();
             return false;
        }else{
             $("#projectPicker").fadeOut();
        }
    });

so if the dialog is opened, any other element that is clicked on the page would close the dialog.

burntblark
honestly i wouldn't bind everything just for something like this.
Matt
yea I guess. Eran's better. actually I wanted to delete this after I saw his. :p
burntblark