42

I have a jQuery dialog box that is meant to position in the middle of the screen. However, it seems slightly off-center vertically.

Here is the code:

$('#add_box').dialog({
    autoOpen: true,
    width: 300,
    modal: true,
    resizable: false,
    bgiframe:true
});

Any ideas why this won't center?

David
  • 16,246
  • 34
  • 103
  • 162
  • How about a screen shot? Does it seem off-center, or *is* it off-center? – Matt Ball Sep 23 '09 at 16:26
  • why the slashes in your selector? – geowa4 Sep 23 '09 at 17:14
  • oh yeah, and people perceive the gap above an object larger than it really is. that's why some artists make the top gap shorter when framing. i wouldn't be surprised if the dialog guys did something similar for aesthetics. – geowa4 Sep 23 '09 at 17:16
  • 1
    You also need to set the height of the dialog to get the verticle correct when initialising –  Aug 13 '12 at 17:53

24 Answers24

51

If your viewport gets scrolled after the dialog displays, it will no longer be centered. It's possible to unintentionally cause the viewport to scroll by adding/removing content from the page. You can recenter the dialog window during scroll/resize events by calling:

$('my-selector').dialog('option', 'position', 'center');
Ken Browning
  • 28,693
  • 6
  • 56
  • 68
  • 1
    This solution did not solve the issue. This allowed the dialog to scroll in some cases, but is was not scrolling in a manner I would deem acceptable for a production level page. The scroll was very jumpy and in firefox was actually reversed scroll. The main reason for voting down is that the dialog still opens off screen. – Nick Benedict Jun 11 '12 at 15:17
  • 3
    My issue was that I was ajax loading / showing content after creating the modal window, so that it was not centered based on the content itself. – Steph Rose Aug 17 '12 at 14:04
  • used after the creation of dialog. Worked of me. – Imran Ali Apr 16 '15 at 03:43
35

Are you adding jquery.ui.position.js to your page? I had the same problem, checked the source code here and realized I didn't add that js to my page, after that.. dialog magically centered.

Andrew
  • 4,953
  • 15
  • 40
  • 58
Eugenio Miró
  • 2,398
  • 2
  • 28
  • 38
  • 2
    You'll also need jquery.ui.draggable.js if you want to drag the dialog. – Matt Apr 01 '11 at 03:20
  • 4
    For anyone still looking for a solution, this is not relevant anymore. – Adrian May 29 '18 at 13:28
  • 1
    This is pretty example code that solve problem with vertical centering of JQuery UI Dialog. Solution is that if you miss vertical centering will not work properly. If you have in your HTML code this declaration it will work correctly ha ha !!! – user5332 May 26 '21 at 09:06
  • This saved me hours. I had deleted !doctype from the html tag and my modals would pop up below the screen window. – birchy Jul 15 '22 at 05:08
28

Digging up an old grave here but for new Google searchers.

You can maintain the position of the model window when the users scrolls by adding this event to your dialog. This will change it from absolutely positioned to fixed. No need to monitor scrolling events.

open: function(event, ui) {
    $(this).parent().css('position', 'fixed');
}
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
jfraser
  • 300
  • 3
  • 7
14

I was having the same problem. It ended up being the jquery.dimensions.js plugin. If I removed it, everything worked fine. I included it because of another plugin that required it, however I found out from the link here that dimensions was included in the jQuery core quite a while ago (http://api.jquery.com/category/dimensions). You should be ok simply getting rid of the dimensions plugin.

coryvb123
  • 412
  • 1
  • 6
  • 12
  • 3
    Thank you, it seems there are many good, correct answers in this thread. This one happened to be the one that applied to me. – mockobject May 31 '11 at 15:47
11

1.) The jQuery dialog centers in whatever element you put it in.

Without more information, my guess is that you have a body div with a margin or something of the like. Move the popup div to the body level, and you'll be good to go.

2.) If you dynamically add content to the div as you load it, centering will NOT be correct. Do NOT display the div until you have the data your'e putting in it.

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
11

Add this to your dialog declaration

my: "center",
at: "center",
of: window

Example :

$("#dialog").dialog({
       autoOpen: false,
        height: "auto",
        width: "auto",
        modal: true,
        position: {
            my: "center",
            at: "center",
            of: window
        }
})
Nick Shaw
  • 2,083
  • 19
  • 27
Taksh
  • 431
  • 4
  • 8
  • 1
    I believe you need to put `my` `at` `of` in a `position` object: $("#dialog").dialog({ autoOpen: false, height: "auto", width: "auto", modal: true, position: { my: "center", at: "center", of: window } }) – AndrewL Jul 24 '19 at 10:27
  • Fixed the example with @AndrewL's note – Nick Shaw Jul 31 '20 at 12:50
  • This saved me :) - Thanks so much! –  Oct 21 '20 at 03:03
10

Simply add below CSS line in same page.

.ui-dialog 
{
position:fixed;
}
Raj
  • 3,890
  • 7
  • 52
  • 80
9

To fix this issue I made sure my body height was set to 100%.

body { height:100% }

This also maintains the center position while the user scrolls.

user781058
  • 113
  • 1
  • 4
4

This issue is often related to opening the dialog via an anchor tag (<a href='#' id='openButton'>Open</a>) and not preventing the default browser behaviour in the handler e.g.

$('#openButton').click(function(event) {
   event.preventDefault();
   //open dialog code...
});

This usually removes the need for any positioning / scrolling plugins.

Rob Willis
  • 4,706
  • 2
  • 28
  • 20
3

For me jquery.dimensions.js was the Culprit

Eswar
  • 31
  • 1
  • This jquery.dimensions.js was part of the tooltip plugin i used and it caused the problem – Satya Jun 02 '12 at 07:03
2

I was facing the same issue of having the dialog not opening centered and scrolling my page to the top. The tag that I'm using to open the dialog is an anchor tag:

<a href="#">View More</a>

The pound symbol was causing the issue for me. All I did was modify the href in the anchor like so:

<a href="javascript:{}">View More</a>

Now my page is happy and centering the dialogs.

Jimbo
  • 191
  • 1
  • 1
  • 9
  • This fixed my situation as well. For me, on the initial open of the dialog, it scrolled to the top and then opened my dialog centered in the window. On any additional opens of the dialog, it opened the dialog centered in the window, and then scrolled to the top, leaving the dialog partially/all off page. Doing as suggested above prevented that scrolling to the top and all worked as expected. – eol May 09 '13 at 16:17
2

My Scenario: I had to scroll down on page to open dialog on a button click, due to window scroll the dialog was not opening vertically center to window, it was going out of view-port.

As Ken has mentioned above , after you have set your modal content execute below statement.

$("selector").dialog('option', 'position', 'center');

If content is pre-loaded before modal opens just execute this in open event, else manipulate DOM in open event and then execute statement.

$( ".selector" ).dialog({
open: function( event, ui ) {
//Do DOM manipulation if needed before executing below statement
$(this).dialog('option', 'position', 'center');
}
});

It worked well for me and the best thing is that you don't include any other plugin or library for it to work.

Sanjeev
  • 2,607
  • 22
  • 16
2
$('#dlg').dialog({
    title: 'My Dialog',
    left: (parseInt(jQuery(window).width())-1200)/2,
    top:(parseInt(jQuery(window).height())-720)/2,
    width: 1200,
    height: 720,
    closed: false,
    cache: false,
    modal: true,
    toolbar:'#dlg-toolbar'
});
1

None of the above solutions seemed to work for me since my code is dynamically generating two containting divs and within that an un-cached image. My solution was as follows:

Please note the 'load' call on img, and the 'close' parameter in the dialog call.

var div = jQuery('<div></div>')
                  .attr({id: 'previewImage'})
                  .appendTo('body')
                  .hide();
var div2 = jQuery('<div></div>')
                  .css({
                      maxWidth: parseInt(jQuery(window).width() *.80) + 'px'
                      , maxHeight: parseInt(jQuery(window).height() *.80) + 'px'
                      , overflow: 'auto'
                  })
                  .appendTo(div);
var img = jQuery('<img>')
                  .attr({'src': url})
                  .appendTo(div2)
                  .load(function() {
                      div.dialog({
                          'modal': true
                          , 'width': 'auto'
                          , close: function() {
                               div.remove();
                          }
                      });
                  });
shmuel613
  • 1,702
  • 1
  • 15
  • 17
  • Going to give a try. Showing the modal only after image loads successfully seems to be tricky. If it takes too long to load image, perhaps I should show some kind of 'loading..' message to save my user from being perplexed. – Sangam Uprety Jun 07 '17 at 11:18
1
$("#dialog").dialog({
       autoOpen: false,
        height: "auto",
        width: "auto",
        modal: true,
         my: "center",
         at: "center",
         of: window
})

This solution does work but only because of the newer jQuery versions ignoring this completely and falling back to the default, which is exactly this. So you can just remove position: 'center' from your options if you just want the pop up to be centered.

Anto S
  • 2,448
  • 6
  • 32
  • 50
1

I had to add this to the top of my HTML file: <!doctype html>. I did not need to set the position property. This is with jQuery 3.2.1. In 1.7.1, that was not needed.

user2233706
  • 6,148
  • 5
  • 44
  • 86
1

Just solved the same problem, the issue was that i did not imported some js files, like widget.js :)

vach
  • 10,571
  • 12
  • 68
  • 106
0

This is how I solved the issue, I added this open function of the dialog:

  open: function () {
                $('.ui-dialog').css("top","0px");                                
                    }

This now opens the dialog at the top of the screen, no matter where the page is scrolled to and in all browsers.

Nick Benedict
  • 547
  • 1
  • 3
  • 12
0

to position the dialog in the center of the screen :

$('#my-selector').parent().position({
                    my: "center",
                    at: "center",
                    of: window
});
Gerard de Visser
  • 7,590
  • 9
  • 50
  • 58
0

I had the same problem, which was fixed when I entered a height for the dialog:

$("#dialog").dialog({
    height: 500,
    width: 800
});
Carl
  • 5
  • 2
0

You must add the declaration

At the top of your document.

Without it, jquery tends to put the dialog on the bottom of the page and errors may occur when trying to drag it.

thedrs
  • 1,412
  • 12
  • 29
0

I was upgrading a legacy instance of jQuery UI and found that there was an extension to the dialog widget and it was simply using "center" instead of the position object. Implementing the position object or removing the parameter entirely worked for me (because center is the default).

Will Strohl
  • 1,646
  • 2
  • 15
  • 32
0

None of the above solutions worked for me. I will present below my scenario and the final solution, just in case someone has the same problem.

Scenario: I use a custom jQuery plugin to add a scroll bar to an HTML element that is located inside the Dialog box.

I used it as

$(response).dialog({
 create: function (event, ui) {
  $(".content-topp").mCustomScrollbar();
 })
});

The solution was to move it from create to open, like this:

$(response).dialog({
 open: function (event, ui) {
  $(".content-topp").mCustomScrollbar();
  $(this).dialog('option', 'position', 'center');
 })
});

So, if you use any custom jQuery plugin that manipulates the content then call it using the open event.

Alexandru Burca
  • 427
  • 1
  • 4
  • 15
0

Solved... Solution of this problem is missing declaration <!doctype html> in HTML code. If you have not this declaration there. Vertial centering of JQuery UI dialog were not working correctly.

user5332
  • 758
  • 2
  • 9
  • 17