Close jQuery Dialog Box when clicked outside of the dialog popup

No Doubt,  jQuery dialog box is one of the widely used UI components. It is not only easy to use but highly customize able and I have been using it a lot in my work.

However, I came upon this issue once,  the widget itself doesn't have an option to close the dialog box whenever user clicks anywhere outside the dialog box.  There are other blogs out there, which uses their own custom method to close the box whenever clicked outside which is helpful but  it didn't help me since I had already used dialog in many places (more than 20 time) and calling the custom method on every dialog initialization was not an option. So I came out with a way to make it dynamic and will work for all the dialog used in an application.

Here is the final code:
//extend jQuery Dialog widget.
$.widget( "ui.dialog", $.ui.dialog, {
    // customize open method to register the click
    open: function() {
       var me = this;
       $(document).on('click',".ui-widget-overlay",function(e){
          //call dialog close function
          me.close();
       });

       // Invoke parent open method
       this._super();
    },
    close: function() {
        // Remove click handler for the current .ui-widget-overlay
        $(document).off("click",".ui-widget-overlay");
        // Invoke parent close method
        this._super(); 
    }
});
I recommend to add this to separate js file and load this file wherever needed (after loading the jQuery UI, preferably in header) or paste above code where needed.
Make sure modal option is set to true
$( "#dialog" ).dialog({
    modal:true
});
View on  github
View on Fiddle

Update:
Without using modal
//extend jQuery Dialog widget.
$.widget("ui.dialog", $.ui.dialog, {
    // customize open method to register the click
    open: function () {
        var me = this;
        $(document).on('click', function (e) {
            if ($(e.target).closest($(me.uiDialog)).length === 0) {

                //call dialog close function
                me.close();
            }
        });

        // Invoke parent open method
        this._super();
    },
    close: function () {
        // Remove click handler for the current .ui-widget-overlay
        $(document).off("click");
        // Invoke parent close method
        this._super();
    }
});

$("#dialog").dialog({
   //modal: true
});
View on Fiddle

Please feel free to comment if you need clarification or you have some other good ways to do so.

Comments

Popular posts from this blog

jquery attr() vs prop() (difference)

Jquery 'On' (Events,Direct ,Delegated)

PHP Profiling Using Xdebug and Kcachegrind