简体   繁体   中英

Close jQuery UI dialog on overlay click

I want to close my modal when people click the overlay, normally u would use

jQuery('.ui-widget-overlay').bind('click', function() {
            jQuery('#dialog').dialog('close');
        })

but i am loading my modal after i create it, so it would seem that the above code interferes with mine somehow. this is my code so far.

 var dialog = $(".dialog").dialog({ autoOpen: false, closeText: "", width: 'auto', modal: true, position: { my: "center top", at: "center top+30", of: "body" }, show: { effect: 'fade', duration: 250, }, hide: { effect: 'fade', duration: 250 }, }); $(".currentDay").click(function () { var id = event.target.id; var url = '/Home/CalenderPartial/' + id; dialog.load(url, function () { dialog.dialog("open"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

You can bind the event inside the open method

var dialog = $(".dialog").dialog({
  autoOpen: false,
  closeText: "",
  width: 'auto',
  modal: true,
  open: function(event, ui) {   //added here
    jQuery('.ui-widget-overlay').on('click', function() {
      jQuery('#dialog').dialog('close');
    });
  },
  position: {
    my: "center top",
    at: "center top+30",
    of: "body"
  },
  show: {
    effect: 'fade',
    duration: 250,

  },
  hide: {
    effect: 'fade',
    duration: 250
  },

});

Okay i found the problem. i was trying to close the dialog before it was initialized.

  var dialog = $(".dialog").dialog({ autoOpen: false, closeText: "", width: 'auto', modal: true, position: { my: "center top", at: "center top+30", of: "body" }, show: { effect: 'fade', duration: 250, }, hide: { effect: 'fade', duration: 250 }, open: function () { jQuery('.ui-widget-overlay').on('click', function () { dialog.dialog('close'); }); }, }); $(".currentDay").click(function () { var id = event.target.id; var url = '/Home/CalenderPartial/' + id; dialog.load(url, function () { dialog.dialog("open"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

this is the code i ended up with, and this works as intended.

so to summarize, put this code inside your dialog init.

open: function() {
        jQuery('.ui-widget-overlay').on('click', function() {
            jQuery('#dialog').dialog('close');
        })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM