Search code examples
jqueryjquery-uidrag-and-dropjquery-dialog

jQuery UI dialog: wrong position if scrollbars are visible


I have a big container with scrollbars.

A modal dialog with jquery UI shall open in the middle of this container.

The dialog opens, but after closing and opening again and again it moves up or down (and so it always has a wrong position).

I've added from this thread Can JQuery UI Dialog remember its position between opening and closing the following part:

beforeclose: function(){
   $(this).dialog('option', 'position', [$(this).offset().left, $(this).offset().top]);
}

If I remove this part, then the dialog opens after dragging/moving it around alway on top of the page.

Also, if the dialog is opened at the bottom, the movings are even crazier.

My code:

$("#btnTest").click(function(){
  if ($("#exec").length == 0) {

            $('body').append('<div id="exec" style="width:320px;background-color: #000;display:none;">xxx</div>');

          $("#exec").dialog({
            width: 320,
            modal: true,
            position: "center",
            show: { effect: "slide", direction: "up", duration: 400 },
            hide: { effect: "slide", direction: "up", duration: 400 }
         });
       } else {
            $("#exec").dialog("open");
        }
 });

$("#btnClose").click(function(){
    $("#exec").dialog('close');
});

Check it @ jsfiddle: http://jsfiddle.net/EDkk6/4/


Solution

  • There appears to be a 20px difference in the top position of the modal when it is reopened. I believe this is because the UI dialog is created within a parent div which you are not taking account for in your offset. Therefore, you need to get the offset based on the parent like so:

    beforeclose: function () {
        var $parent = $(this).parent();
    
        $(this).dialog('option', 'position', [$parent.offset().left,$parent.offset().top]);
    }
    

    Live DEMO