GTS Joe
GTS Joe

Reputation: 4142

jQuery UI Dialog: Close when Click Outside

I have a jQuery UI Dialog. I tried implementing the "$('.ui-widget-overlay').bind('click'...." method which has been suggested to close the dialog when a user clicks outside. However, it doesn't work in my code. What am I doing wrong?

$('input[name="delete-image"]').click(function(e){
    e.preventDefault();
    $("div.deleteImageDialog").dialog({
        resizable: false,
        modal: true,
        buttons: {
            "OK": function(e) {
                e.preventDefault();
                $.ajax({
                    url: $('form.addEdit').attr('action'),
                    type: $('form.addEdit').attr('method'),
                    data: $('form.addEdit').serialize(),
                    open: function(){
                                $('.ui-widget-overlay').bind('click', function(){
                                    $('div.deleteImageDialog').dialog('close');
                                })
                    },
                    success: function(html) { }
                });
                $(this).dialog('close');
            },
            "Cancel": function() {
                $(this).dialog('close');
            }
        }
    });

});

Upvotes: 1

Views: 5147

Answers (2)

AppGeer
AppGeer

Reputation: 745

Then you have to bind an event to the overlay.

$('input[name="delete-image"]').click(function(e){
    e.preventDefault();
    $("div.deleteImageDialog").dialog({
            // your code...
            "Cancel": function() {
                $(this).dialog('close');
            }
        }
    });
    $('.overlay_sector').bind( 'click', function() {
            $("div.deleteImageDialog").dialog('close');
            $('.overlay_sector').unbind();
    } )
});

Upvotes: 5

MTran
MTran

Reputation: 1809

I had a similar problem. Went with a simpler code solution based on this thread's answer:

Use jQuery to hide a DIV when the user clicks outside of it

    $(document).mouseup(function (e)
    {
        var myDialog = $("#dialog-confirm");
        var container = $(".ui-dialog");

        if (myDialog.dialog( "isOpen" )===true) 
        {
            if (!container.is(e.target) // if the target of the click isn't the container...
                && container.has(e.target).length === 0) // ... nor a descendant of the container
            {
                myDialog.dialog( "close" );
            }
        }
    });

Upvotes: 2

Related Questions