user3746789
user3746789

Reputation: 73

Set jQuery UI dialog's position relative to the element that opened it

I'm trying to position a jQueryUI dialog above the element that was clicked to trigger its open.

I've tried the following, but it isn't working.

$(function() {
    dialog = $( "#gridDialog" ).dialog({
    autoOpen: false,
    modal: true,
    buttons: {
        "Close": function(event, ui) {
            dialog.dialog( "close" );
         }
    },
    open: function(event,ui){
        dialog.dialog( "option", "position", {at: "left top", of: event } );
    }
  });           
});

Upvotes: 7

Views: 7901

Answers (1)

T J
T J

Reputation: 43156

The issue with your approach is that you're trying to position the dialog inside it's own open() method, which receives a custom jQuery UI event object, that doesn't have pageX and pageY properties which is expected by the jQuery UI position() method.

Instead if you set the position of dialog inside the click event handler before opening it, You can simply passthis, or the click event object as the value of position() option's of property.

For example:

 $("#dialog").dialog({
   autoOpen: false
 });
 $(".box").click(function() {
   $("#dialog").dialog("option", "position", {
     at: "left top",
     of: this // this refers to the cliked element
   }).dialog("open");
 });
.box {
  width: 100px;
  height: 100px;
  background: dodgerblue;
}
#left {
  float: left;
}
#right {
  float: right;
}
<link href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div id="left" class="box"></div>
<div id="right" class="box"></div>
<div id="dialog" title="Basic dialog">
  <p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>

Upvotes: 8

Related Questions