0

I am playing around with jQuery UI. I wanted to dynamically display dialog box, when the user clicks the body element. While the dialog displays, I cannot close it. Moreover, if the dialog displays at page load, closing is possible.

$("body").click(function(e){
   $("#dialog").dialog({
        title:"Title here",
        buttons:{
            Update:function(){$(this).dialog("close");},
            Cancel:function(){$(this).dialog("close");}
        }
    });
});

JSBin

Any idea what am I missing?

1
  • I think that $(this) refers back to your $("body") Commented Mar 20, 2017 at 14:04

1 Answer 1

1

Hope this might help you.

With this line if ($(e.target).find('#dialog').length !== 0) {}) we ask if the element we have clicked on is NOT our $(dialog)

$("body").click(function(e) {
  if ($(e.target).find('#dialog').length !== 0) {
    $("#dialog").dialog({

      title: "Tistle here",
      buttons: [{
          text: "Update",
          click: function() {
            $("#dialog").dialog("close");
          }
        },
        {
          text: "close",
          click: function() {
            $("#dialog").dialog("close");
          }
        }
      ]
    });
  }
});
body {
  height: 100vh;
  background-color: red;
}
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<div id="dialog"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate! This works, but I am unsure why is it necessary to check if user didn't click #dialog. If you have time, can you elaborate?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.