How to auto-center jQuery UI dialog when resizing browser?

Alternatively to Ellesedil's answer,

That solution did not work for me straight away, So I did the following which is also dynamical but shortened version:

$( window ).resize(function() {
    $(".ui-dialog-content:visible").each(function () {
        $( this ).dialog("option","position",$(this).dialog("option","position"));
    });
});

+1 for Ellesedil though

EDIT:

Much shorter version which works great for single dialogs:

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

It is not necessary for .each() to be used perhaps if you have some unique dialogs which you dont want to touch.


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. ​