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:
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.
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.
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');
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
}
})
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.
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(); } }); });