How to close a jQuery dialog box by clicking outside of it

JQuery gives you a very simple way to create dialog overlays with the dialog() event. So, by clicking an HTML element you can activate a “stay-on-the-page” overlay dialog box.

Traditionally one might use dialog boxes to ask the user a question to which she must respond (e.g. with an “Ok” or “Cancel”) but their use can extend beyond this. For instance I’ve used a dialog to show a mega drop-down menu; i.e. clicking a link opens a dialog box with a list of categorised links.

JQuery’s default behaviour for closing dialog boxes is not unreasonable: the user must click on the “Close” button (e.g. in the form of text or an “x”) or hit the escape key. However it’s possible you may want to provide more options for your users to close a box by simply clicking outside it.

I puzzled over this and didn’t get very far with Googling but came up with the following solution which seems to work.

When your dialog is created, a div with the class “ui-widget-overlay” is also created which “greys out” the background allowing the user to fully focus on the dialog. You can use this as a hook to add your dialog closing code, e.g.


$(".ui-widget-overlay").live("click", function() {  $("#quick-links-modal").dialog("close"); } );

In this case my dialog has the ID “quick-links-modal”. NB you need to use the “live” event (rather than “click” etc.)  in order to bind the event to your dialog before the dialog has been initiated.

Tags: UI, blog-post, javascript, jquery, web design, web development.

4 Responses to “How to close a jQuery dialog box by clicking outside of it”

  1. Marty says:

    If you could show an example with html and all, it would be awesome.

  2. Marty says:

    Perhaps this will work as an example:

    jQuery portion:

    $(function(){
    // Dialog
    $('#dialog').dialog({
    autoOpen: false,
    width: 600,
    modal: true, //there is no overlay (.ui-widget-overlay) if modal is false or not set.
    buttons: {
    "Close": function() {
    $(this).dialog("close");
    }
    }
    });

    //closes the dialog window if the user clicks outside of the window.
    $(".ui-widget-overlay").live("click", function() { $("#dialog").dialog("close"); } );

    // Link to open the dialog box
    $('#dialog_link').click(function(){
    $('#dialog').dialog('open');
    return false;
    });
    });

    HTML portion:

    Open Dialog

  3. David says:

    Hi Marty, thanks for the example. I’ll see if I can something up too when I have a chance.

  4. Marty says:

    I can’t leave the html portion. I tried to send it to you on twitter, but don’t know if it went since you don’t follow me. Anyway, it is a link with the id of dialog.

    Thanks for the jquery; it saved me figuring it out.

Archives