10

I'm toying with jQuery UI, and I like how this demo works: http://jqueryui.com/demos/dialog/#modal-message

However, when a dialog comes up, the only way to close it is to click one of the interface buttons inside the dialog - how could I extend this to close any/a given dialog when the user clicks on the background layer covering up the page?

I saw where users can hit "escape", but frankly I don't think most users will think to do this (I didn't until I saw it as an option), however it might occur to them to click away from the message.

Is there an event/option I'm missing that I can tap into?

Jane Panda
  • 1,549
  • 4
  • 23
  • 49
  • 2
    I found the answer at http://stackoverflow.com/questions/1675893/jquery-close-dialog-on-click-anywhere to work better than the ones listed here. – Nils Apr 24 '12 at 03:33

5 Answers5

17

That should do the trick:

$(".ui-widget-overlay").click(function(){
    $(".ui-dialog-titlebar-close").trigger('click');
});

Click on .ui-widget-overlay will trigger the click on the close button

Cheers

G.

Greg
  • 1,354
  • 10
  • 11
14

I've found the previous to be finicky at times, here's a simple fix:

$(".ui-widget-overlay").live('click', function(){
   $(".ui-dialog-titlebar-close").trigger('click');
});
Tim Cooper
  • 151,519
  • 37
  • 317
  • 271
KidCache
  • 161
  • 7
  • You know I had to ask about live a few days after this, heh. – Jane Panda Jan 31 '11 at 15:42
  • How would you apply the background click in IE6 environment? It's failing on my side at the moment. I'm using latest [Github]https://github.com/jquery/jquery-ui/commit/04667b15180ddbbc88af9a0fe30ace91aef2ae15 – KidCache Feb 11 '11 at 15:17
  • live is better according to my testing! – Keltex Jun 21 '11 at 17:59
13

This one will definitely work, since it matters when the overlay is in the dom or not.

$(document).on('click', '.ui-widget-overlay', function(){
  $(".ui-dialog-titlebar-close").trigger('click');
});
Ian Davis
  • 18,353
  • 26
  • 83
  • 127
3

just to add in case anyone run's into this problem - if you have multiple dialogs stacked on top of each other then the following will close just the dialog that's at the top:

$(".ui-widget-overlay").live("click", function () {
            $(".ui-dialog-titlebar-close", $(this).prev()).trigger('click');
        });
Ian Routledge
  • 3,897
  • 1
  • 21
  • 24
1

This is the preferred method to use when dealing with newer versions of Jquery.

$(".ui-widget-overlay").on("click", function(){
    $(".ui-dialog-titlebar-close").trigger('click');
});
Case
  • 4,122
  • 5
  • 33
  • 50