Jquery – How to auto-center jQuery UI dialog when resizing browser

jqueryjquery-uimodal-dialog

When you use jquery UI dialog, all works well, except for one thing.
When the browser is resized, the dialog just stays in it's initial position which can be really annoying.

You can test it out on:
http://jqueryui.com/demos/dialog/

Click on the "modal dialog" example and resize your browser.

I'd love to be able to let dialogs auto-center when the browser resizes.
Can this be done in an efficient way for all my dialogs in my app?

Best Answer

Setting the position option will force this, so just use the same selector covering all your dialogs where I use #dialog here (if it doesn't find them no action is taken, like all jQuery):

jQuery UI before 1.10

$(window).resize(function() {
    $("#dialog").dialog("option", "position", "center");
});

jQuery UI 1.10 or higher

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

Here's that same jQuery UI demo page adding only the code above, we're just adding a handler to the window's resize event with .resize(), so it triggers the re-center at the appropriate time. ​