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?
Thanks a lot!
A more comprehensive answer, which uses Nick's answer in a more flexible way can be found here.
An adaption of the code of relevance from that thread is below. This extension essentially creates a new dialog setting called autoReposition which accepts a true or false. The code as written defaults the option to true. Put this into a .js file in your project so that your pages can leverage it.
This allows you to supply a "true" or "false" for this new setting when you create your dialog on your page.
Now this dialog will always reposition itself. AutoReposition (or whatever you call the setting) can handle any dialogs that do not have a default position and automatically reposition them when the window resizes. Since you're setting this when you create the dialog, you don't need to identify a dialog somehow because the repositioning functionality becomes built into the dialog itself. And the best part is that since this is set per dialog, you can have some dialogs reposition themselves and others remain where they are.
Credit to user scott.gonzalez on the jQuery forums for the complete solution.
Another CSS-only option which works is this. The negative margins should equal half your height and half your width. So in this case, my dialog is 720px wide by 400px tall. This centers it vertically and horizontally.
Alternatively jQuery ui position can be used,
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
jQuery UI 1.10 or higher
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. 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:
+1 for Ellesedil though
EDIT:
Much shorter version which works great for single dialogs:
It is not necessary for .each() to be used perhaps if you have some unique dialogs which you dont want to touch.
Hello everyone!
Vanilla JS solution: