Pages

Search This Blog

Tuesday, 7 January 2014

Close the jQuery dialog when clicked anywhere on the page

You would have created a jQuery dialog and it will be opened on few cases. there will be requirement where the dialog should be closed when user clicks anywhere on the page. The following code piece does the trick:

$(document).ready(function () {
         //the dialog should close when clicking anywhere else on the page
             $('body').on('click', function (event) {
                     $("#dialog").dialog("close");
             });
});

The above code will work fine but the dialog will be closed even when the click event occurs on the dialog. So to avoid that check whether the click event is not on the dialog. Code below works as expected.

$(document).ready(function () {
      //the dialog should close when clicking anywhere else on the page
      $('body').on('click', function (event) {
                  var parent = $(event.target).closest("div");
                   if (!(parent.attr('id') == "dialog"))
                          $("#dialog").dialog("close");
});
});


Usually Dialog is created with help of an div tag, so check the ID of the closest div where the click event occured

 

No comments:

Post a Comment