How can I implement, that a jQuery modal dialog with auto width & height is always centered in the browser. Also after resizing the window of the browser.
The following code doesn't work. I think the problem is the auto width & height.
jQuery - code
$("<div class='popupDialog'>Loading...</div>").dialog({
autoOpen: true,
closeOnEscape: true,
height: 'auto',
modal: true,
title: 'About Ricky',
width: 'auto'
}).bind('dialogclose', function() {
jdialog.dialog('destroy');
}).load(url, function() {
$(this).dialog("option", "position", ['center', 'center'] );
});
$(window).resize(function() {
$(".ui-dialog-content").dialog("option", "position", ['center', 'center']);
});
Thank you!
Acutally, I think the position: ["center", "center"]
not be the best solution, as it assigns an explict top:
and left:
css properties to the dialog based on the size of the viewport at creation.
I came across this same issue when trying to have a dialog center on screen vertically. Here is my solution:
In the options
part of my .dialog()
function, I pass position:[null, 32]
. The null
sets the left:
value the element's style, and the 32
is just for keeping the dialog box pegged to the top of the window. Also be sure to set an explicit width.
I also use the dialogClass
option to assign a custom class, which is simply a margin:0 auto;
css property:
.myClass{
margin:0 auto;
}
And my dialog looks like:
$('div#popup').dialog({
autoOpen: false,
height: 710,
modal: true,
position: [null, 32],
dialogClass: "myClass",
resizable: false,
show: 'fade',
width: 1080
});
Hopefully this helps someone.
$(window).resize(function() {
$("#dialog").dialog("option", "position", "center");
});
Working jsFiddle: http://jsfiddle.net/vNB8M/
The dialog is centered with auto width & height and continues to be centered after window resize.
None of the answers did quite what I wanted. For those that are still having problems with this, here is what worked for me. This will force the dialog to always appear in the center of the screen, and it will center the dialog as the browser is resized.
$( "#ShowDialogButton" ).click(function(){
$( "#MyDialog" ).dialog({
show: 'fade'
}).dialog( "option", "position", { my: "center", at: "center", of: window } );
$(window).resize(function() {
$( "#MyDialog" ).dialog( "option", "position", { my: "center", at: "center", of: window } );
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With