0

I am trying to close the jQuery dialog when clicked anywhere outside the dialogue box

I have tried with this code:

$("#dialog").dialog({
  modal: false,
  autoOpen: false,
  height: "auto",
  width: "auto",
  open: function() {
    jQuery('.ui-widget-overlay').bind('click', function() {
      jQuery('#dialog').dialog('close');
    })
  }
});

But it is not able to close the Jquery diaog when clicked anywhere outside the box

http://jsfiddle.net/ovog4njt/30/

I dont have any custom css as mentioned in the fiddle pointed by OP

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Kiran
  • 59
  • 7
  • Why are you using `.ui-widget-overlay` selector? There's no such element. Also, you are using old jQuery UI version which cause errors. – Michał Perłakowski Jan 10 '16 at 17:37
  • i have taken some fiddle and used my code in it , so i dont know about version exactly. – Kiran Jan 10 '16 at 17:39
  • I have taken the answer from the duplicate link pointed by OP and whic aren't working ( open: function(){ jQuery('.ui-widget-overlay').bind('click',function() { jQuery('#dialog').dialog('close'); })) – Kiran Jan 10 '16 at 17:46

1 Answers1

1

The reason your code isn't working is because modal is set to false, which means that there is no .ui-widget-overlay element. To resolve this, you could simply set modal to true when initializing the dialog, and it will work as expected. (updated example)

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

However, if you can't change that for some reason, or if you don't want the dialog to be a modal, an alternative would be to attach a click event listener to the document, and determine whether event.target is inside of the dialog element:

Working Example

$("#dialog").dialog({
  modal: false,
  autoOpen: false,
  height: "auto",
  width: "auto",
  open: function() {
    var self = this;
    $(document).one('click', function(e) {
      if (!$(e.target).closest('.ui-dialog').length) {
        $(self).dialog('close');
      }
    });
  }
});

You will also need to stop immediate propagation when opening the dialog in order to prevent it from being closed immediately:

$('#open').click(function(e) {
  e.preventDefault();
  e.stopImmediatePropagation();
  $("#dialog").dialog('open');
});
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304