views:

507

answers:

3

I have a jQuery UI Dialog that gets displayed when specific elements are clicked. I would like to close the dialog if a click occurs anywhere other than on those triggering elements or the dialog itself.

Here's the code for opening the dialog:

$(document).ready(function() {
    var $field_hint = $('<div></div>')
        .dialog({
            autoOpen: false,
            minHeight: 50,
            resizable: false,
            width: 375
        });

    $('.hint').click(function() {
        var $hint = $(this);
        $field_hint.html($hint.html());
        $field_hint.dialog('option', 'position', [162, $hint.offset().top + 25]);
        $field_hint.dialog('option', 'title', $hint.siblings('label').html());
        $field_hint.dialog('open');
    });
    /*$(document).click(function() {
        $field_hint.dialog('close');
    });*/
});

If I uncomment the last part, the dialog never opens. I assume it's because the same click that opens the dialog is closing it again.


Final Working Code

$(document).ready(function() {
    var $field_hint = $('<div></div>')
        .dialog({
            autoOpen: false,
            minHeight: 50,
            resizable: false,
            width: 375
        })
        .bind('clickoutside', function(e) {
            if (!$(e.target).filter('.hint').length) {
                $field_hint.dialog('close');
            } 
        });

    $('.hint').click(function() {
        var $hint = $(this);
        $field_hint.html($hint.html());
        $field_hint.dialog('option', 'position', [162, $hint.offset().top + 25]);
        $field_hint.dialog('option', 'title', $hint.siblings('label').html());
        $field_hint.dialog('open');
    });
});
+1  A: 

Check out the jQuery Outside Events plugin

Lets you do:

$field_hint.bind('clickoutside',function(){
    $field_hint.dialog('close');
});
PetersenDidIt
I'm getting the same behavior, in that the hint won't display when the $('.hint') elements are clicked. Those elements are 'outside' the dialog.
Sonny
You only care about the click outside if the dialog is open. So only bind it after you open it.
PetersenDidIt
I read in another place about filtering based in the event, and that solved the problem: http://groups.google.com/group/jquery-ui/msg/a880d99138e1e80d
Sonny
The dialog gets reused several times in the document, so I'd have to have a way to unbind when closing the dialog. I think the filtering is a simpler solution.
Sonny
+1  A: 

Try this post:

http://www.jensbits.com/2010/06/16/jquery-modal-dialog-close-on-overlay-click/

jen
I'll take a look at it. Thanks Jen!
Sonny
A: 

Just updated the post this evening. Take another look if you haven't already. Thx.

jen