How can I position my jQuery dialog to center?
Asked Answered
M

22

71

I have tried following code, but it only positions dialogs left upper corner position to center, and that makes element to be aligned to right. How can I center dialog to real center which counts elements width, so that center line will cut dialog to 50% 50% halfs?

$('.selector').dialog({ position: 'center' });

http://docs.jquery.com/UI/Dialog#option-position

Mecham answered 3/12, 2009 at 12:54 Comment(2)
I am having a similar problem to what I am assuming that the OP did. The dialog is positioning in the top left corner no matter what I do! Very frustrating.Portcullis
your tip to use position (center) attr/property solved my similar problem on mobiles. But I use jquery-ui-1.9.2.custom.Shaquitashara
M
51

I'm pretty sure you shouldn't need to set a position:

$("#dialog").dialog();

should center by default.

I did have a look at the article, and also checked what it says on the official jquery-ui site about positioning a dialog : and in it were discussed 2 states of: initialise and after initialise.

Code examples - (taken from jQuery UI 2009-12-03)

Initialize a dialog with the position option specified.

$('.selector').dialog({ position: 'top' });

Get or set the position option, after init.

//getter
var position = $('.selector').dialog('option', 'position');
//setter
$('.selector').dialog('option', 'position', 'top');

I think that if you were to remove the position attribute you would find it centers by itself else try the second setter option where you define 3 elements of "option" "position" and "center".

Marquee answered 3/12, 2009 at 13:14 Comment(1)
Well, the reason for centering is that sometimes you dynamically load content after the dialog is already loaded.Lamee
K
73

The latest jQuery UI has a position component:

$("#myDialog").position({
   my: "center",
   at: "center",
   of: window
});

Doc: http://jqueryui.com/demos/position/
Get: http://jqueryui.com/download

Kamasutra answered 3/9, 2010 at 2:11 Comment(5)
I had trouble with this because it would sometimes change the position of the content of the dialog box but not the outer box, so here is what worked for me: $('#myDialog').dialog('widget').position({my:"center", at:"center", of:window)}Fry
This doesn't work for me on Safari 6.2.3 as I scroll down and trigger this function, the element will be positioned below the viewport.Metrics
@Fry $('#myDialog').dialog('widget') and $('#myDialog').parent() both work.Vine
$('#MyDialog').dialog('option','position',{ my: "center", at: "center", of: window })Afternoon
@JoeDF answer works correctly. But it doesn't work in iOS safari. Does anyone have an idea, why?Heteroousian
M
51

I'm pretty sure you shouldn't need to set a position:

$("#dialog").dialog();

should center by default.

I did have a look at the article, and also checked what it says on the official jquery-ui site about positioning a dialog : and in it were discussed 2 states of: initialise and after initialise.

Code examples - (taken from jQuery UI 2009-12-03)

Initialize a dialog with the position option specified.

$('.selector').dialog({ position: 'top' });

Get or set the position option, after init.

//getter
var position = $('.selector').dialog('option', 'position');
//setter
$('.selector').dialog('option', 'position', 'top');

I think that if you were to remove the position attribute you would find it centers by itself else try the second setter option where you define 3 elements of "option" "position" and "center".

Marquee answered 3/12, 2009 at 13:14 Comment(1)
Well, the reason for centering is that sometimes you dynamically load content after the dialog is already loaded.Lamee
B
20

Because the dialog need a position, You need to include the js position

<script src="jquery.ui.position.js"></script>
Bottleneck answered 28/6, 2012 at 13:14 Comment(2)
Bingo - we have a winner. That was my problem. Thanks!Undersized
excellent! thanks for that. Couldn't work out why it wasn't workingOstracon
M
12
open: function () {

    var win = $(window);

    $(this).parent().css({
        position: 'absolute',
        left: (win.width() - $(this).parent().outerWidth()) / 2,
        top: (win.height() - $(this).parent().outerHeight()) / 2
    });
}
Maccarone answered 3/6, 2015 at 15:28 Comment(14)
i liked this solution, in conjunction with window.scrollTo(0, 0); it works great for me +1Yvetteyvon
@MaVRoSCy, I'm running into a similar issue. If i scroll and then open the dialog, it does not positon to center. How did you use the scrollTo and where do I add it?Sonnnie
@Sonnnie Have you tried using: autoReposition: true, as an initialization parameter of the jquery ui dialog instance? Moreover, you could simply use something like: jQuery(window).on('resize', function() and bind to it a logic similar to the above, but using the described at: api.jqueryui.com/dialog/#method-isOpenMaccarone
I used this code to ensure it was in the middle of a window when there were scroll bars: left: (window.innerWidth - $(this).parent().parent().outerWidth())/2, top: (window.innerHeight - $(this).parent().parent().outerHeight())/2Echelon
@user1527762: At the dialog open annonymous function.. open : function(){ var document= $(document); var win = $(window); /* i guess this.parent is the document, r document could work but is the window what we use to center the dialogs*/ win.scrollTo(0, 0); $(this).parent().css({ position:'absolute', left: (win.width() - $(this).parent().outerWidth())/2, top: (win.height() - $(this).parent().outerHeight())/2 }); },Maccarone
@Blake Parmenter: if the op has freedom to deal with the window perhaps resizeTo(x,y) javascript native function helps to ensure the window or to look for a fullscreen api could work as well :) that is to ensure the jquery ui based dialog window fits well in the screen of the viewer but it might ask for permission to execute and issue can happen if tabbed or pop up blocker is enabled on the nav browserMaccarone
@JeanPaul are you using a plugin for win.scrollTo() method in your comment? In console, I'm getting an error Uncaught Error: TrackJS Caught: win.scrollTo is not a function it appears, scrollTo() is a window method, not a jquery method. Please clarify. Thx.Hullda
@Hullda .. function.. open : function(){ var document= $(document); var win = $(window); ... Actually is a "Javascript" method. win is defined within the dialog open function, feel free to give that a try.Maccarone
Or you could use something more general like: $('a[href^="#"]').on('click', function(event) { var target = $(this.getAttribute('href')); if( target.length ) { event.preventDefault(); $('html, body').stop().animate({ scrollTop: target.offset().top }, 'slow'); } });Maccarone
@JeanPaul, I see you removed the win.scrollTo(0,0) you had originally when I asked about it yesterday. Your original code (snippet): open: function(){ var document = $(document); var win = $(window); win.scrollTo(0,0); $(this).parent().css({ position:'absolute', left: (win.width() - $(this).parent().outerWidth())/2, top: (win.height() - $(this).parent().outerHeight())/2 }); $(window) isn't javascript objHullda
@Hullda I believe you are confused, first of all my answer isn't edited since 2015, 2.) Secondly, a comment is an extension not an answer 3.) I am really not understanding where are you going with this, so if I can help message me off this topic and I will be glad to assist you, if I canMaccarone
comptechdoc.org/independent/web/cgi/javamanual/javawindow.htmlMaccarone
jqfundamentals.com/chapter/jquery-basics @Hullda Please refer to this paragraph " 1 2 // Expose jQuery to the global object window.jQuery = window.$ = jQuery; When you call the $() function and pass a selector to it, you create a new jQuery object. Of course, in JavaScript, functions are objects too, so that means that $ (and jQuery, of course) has properties and methods, too .."Maccarone
all position didn't work for my case, this scripting work.Sabbatical
P
11

So if anyone hits this page like I did, or for when I forget in 15 minutes, I'm using jqueryui dialog version 1.10.1 and jquery 1.9.1 with ie8 in an iframe(blah), and it needs a within specified or it doesn't work, i.e.

position: {
 my: "center bottom",
 at: "center top",
 of: $("#submitbutton"),
 within: $(".content")
}

Thanks to @vm370 for pointing me in the right direction.

Playbill answered 15/3, 2013 at 5:13 Comment(2)
I didn't have to use within but the reason for my up vote is that it uses the position attribute like so: $('.selector').dialog({ position: my: "center bottom", at: "center top", of: $("#submitbutton") }); instead of adding a call at the end: $('.selector').position(...)Goiter
This one makes sense a lot. Thank you.Brainard
X
9

I'm getting best results to put jQuery dialog in the center of browser's window with:

position: { my: "center bottom", at: "center center", of: window },

There's probably more accurate way to position it with option "using" as described in the documentation at http://api.jqueryui.com/position/ but I'm in a hurry...

Xylol answered 10/4, 2015 at 23:9 Comment(1)
This must be in top! Thank youBaobaobab
Z
7

To fix center position, I use:

open : function() {
    var t = $(this).parent(), w = window;
    t.offset({
        top: (w.height() / 2) - (t.height() / 2),
        left: (w.width() / 2) - (t.width() / 2)
    });
}
Zeitgeist answered 2/8, 2013 at 14:18 Comment(2)
I think you need $(w). Plus, this doesn't seem to deal with scrolling in the browser.Sethsethi
@Chris Prince not necessarily, I think that the nav browser is intelligent enough to know that we are referring to the window at that instance, I could be wrong, but indeed if it should be rather w = $(window); a quick fix to that.. This approach is interesting because each time it opens up the dialog it looks for the window, which serves as an on window resize function call, so that's why my upvote, although I must add that normally when I use an open function within the dialog I as well use a this.dialog('destroy') on close, to allow reusability, specially with jQuery UI ThemingMaccarone
J
6

Try this....

$(window).resize(function() {
    $("#dialog").dialog("option", "position", "center");
});
Junto answered 14/5, 2014 at 2:16 Comment(0)
I
6

I have to call function dialog() twice to position the dialog (jQuery v1.11.2 / jQueryUI v1.10.4).

$("#myDialog").dialog({
    /* initial dialog parameters */
}).dialog({
    position: {
        my: "center center",
        at: "center center",
        of: window
    }
});
Ir answered 9/11, 2015 at 14:51 Comment(1)
Me too. Your suggestion fixed me. Have you found a better solution? Somewhere along the line I changed the version of jQuery and this issue started. Downgrading didn't fix it. Update: I mcved the position object to the first parameter group and it still workedCarri
P
5

Jquery UI 1.9.2, jquery and the later versions don' support IE8

I found two solutions for that.

  1. Rollback to jquery UI 1.7.2 to support IE8,

  2. Try this code with Jquery UI 1.9.2

position: {my: "center",  at: "center", of: $("body"),within: $("body") }
Pugilism answered 21/2, 2014 at 6:1 Comment(3)
Works perfectly in IE11 with jQueryUI 1.11.4Bricabrac
+1 because of the within param, which allows docking like on appendTo this element, and if using a modal window allows limiting that docking.Maccarone
at the center of body? That's a bit strange... If your page is a normal webpage (i.e longer than the viewport) your dialog window will appears way outside the view of the User and he will need to scroll down to see it.Massorete
A
4

Another thing that can give you hell with JQuery Dialog positioning, especially for documents larger than the browser view port - you must add the declaration

<!DOCTYPE html>

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.

Answer answered 15/12, 2014 at 13:14 Comment(0)
R
4

Following position parameter worked for me

position: { my: "right bottom", at: "center center", of: window },

Good luck!

Runnels answered 15/5, 2015 at 2:54 Comment(0)
R
3

According to the following discussion, the problem could be due to less IE compatibility in the newer jQuery versions, reverting back to 1.7.2 seems to resolve the problem, which only occurs in IE8. http://forum.jquery.com/topic/jquery-ui-dialog-positioning-not-working-in-ie-8

Rhodesia answered 20/12, 2012 at 10:57 Comment(0)
O
3

I had a problem with this and I finally figured this out. Until today I was using a really old version of jQuery, version 1.8.2.

Everywhere where I had used dialog I had initialised it with the following position option:

$.dialog({
    position: "center"
});

However, I found that removing position: "center" or replacing it with the correct syntax didn't do the trick, for example:

$.dialog({
    position: {
       my: "center",
       at: "center",
       of: window
    }
});

Although the above is correct, I was also using option to set the position as center when I loaded the page, in the old way, like so:

// The wrong old way of keeping a dialog centered
passwordDialogInstance.dialog("option", "position", "center");

This was causing all of my dialog windows to stick to the top left of the view port.

I had to replace all instances of this with the correct new syntax below:

passwordDialogInstance.dialog(
    "option",
    "position", 
    { my: "center", at: "center", of: window }
);
Odel answered 14/4, 2017 at 11:34 Comment(0)
S
2

If you are using individual jquery files or a custom jquery download either way make sure you also have jquery.ui.position.js added to your page.

Smuts answered 23/1, 2012 at 17:13 Comment(0)
A
2

Are you running into this in IE only? If so, try adding this to the FIRST line of your page's HEAD tag:

<meta http-equiv="X-UA-Compatible" content="IE=7" />

I had though that all compatibility issues were fixed in later jQueries, but I ran into this one today.

Alcala answered 13/11, 2012 at 21:49 Comment(0)
C
2

Try this for older versions and somebody who don't want to use position:

$("#dialog-div-id").dialog({position: ['center', 'top'],....
Cystoid answered 14/6, 2013 at 13:39 Comment(0)
P
2

You also need to do manual re-centering if using jquery ui on mobile devices - the dialog is manually positioned via a 'left & top' css property. if the user switches orientation, the positioning is no longer centered, and must be adapted / re-centered afterwards.

Petuntse answered 14/6, 2013 at 22:25 Comment(2)
gekido: Are you suggesting to use this method?Maccarone
it was a while ago when I fought with this but we had a number of issues with jquery dialogs on mobile. basically they worked great - until the user switch orientation of the device. can't remember the specific fix that was applied, but basically we checked to see if the orientation had changed and then repositioned the dialog afterwards. Definitely felt a bit hacky, but it worked.Petuntse
S
2

For Win7/IE9 environment just set in your css file:

.ui-dialog {
   top: 100px;
   left: 350px !important;
}
Shrewmouse answered 22/7, 2013 at 14:20 Comment(0)
B
0

I fixed with css:

.ui-dialog .ui-dialog-content {
  width: 975px!important;
  height: 685px!important;
  position: fixed;
  top: 5%;
  left: 50%;
  margin:0 0 0 -488px;
}
Bacchant answered 14/2, 2014 at 4:18 Comment(0)
F
0

Could not get IE9 to center the dialog.

Fixed it by adding this to the css:

.ui-dialog {
    left:1%;
    right:1%;
}

Percent doesn't matter. Any small number worked.

Fredia answered 30/5, 2014 at 22:45 Comment(0)
U
0
position: {
 my: "center bottom",
 at: "center top",
 of: window,
 within: $(".content")
}
Unknot answered 18/4, 2023 at 17:29 Comment(1)
Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach? That's even more critical in this case, where we have 21 existing answers, one which has been validated by 72 members of the community.Legitimate

© 2022 - 2024 — McMap. All rights reserved.