Jquery – How to center JQuery dialog box after browser resize

jqueryjquery-uijquery-ui-dialog

What I'm trying to do:
When my browser is maximized and I open the JQuery dialog, it opens it in the center as expected. However when I resize the browser to be slightly smaller than the width of the dialog and then open the dialog, it always opens it left-justified. With a chunk of space on the right.

Code

$(document).ready(function() { 
     var dlg = '';

     dlg=$('#ticketDetails').dialog({
        title: 'TICKET DETAILS',
        resizable: true,
        autoOpen:false,
        modal: true,
        show:'fast',
        hide: 'fade',
        buttons:{ "Close": function() { dlg.dialog("close"); } },
        close: function(e, i) { dlg.hide(); },
        width:1250

     });

What I've tried:

$(window).resize(function() {
    $('#ticketDetails').dialog({position: ['center', 'center']});
});

I've read some of the answers and tried a few variations but nothing seems to work..

Further information:

http://jsfiddle.net/39GqM/479/

If you you scroll the bar in the middle all the way to the left and then run it you will notice that to view the dialog content on the right you need to drag it to the left by the title bar and only then the scroll bar will appear.

The following screen is when the browser is on full screen. As you can see the content fits perfectly:
enter image description here

Now the page has been resized and then I've opened the dialog. As you can see its left-justified. There is no scroll-bar and the only way to get the scroll bar is to drag the dialog left (via the cursor that appears on the title) for the scroll bar to appear. This is the only way to see the content on the right (start of the paragraph/ title).
enter image description here

Best Answer

I highly recommend using css media queries to achieve this and use a polyfill as a fallback if you support IE8 and lower.

Here is my solution on jsfiddle:

http://jsfiddle.net/39GqM/505/

    .ui-dialog {
      min-width: 80%;  
      width: 80% !important;
   } 
   @media only screen and (min-width: 1200px) {
     .ui-dialog {
        width: 1000px !important;
    } 
   }

   @media only screen and (max-width: 1000px) {
    .ui-dialog {
        min-width: 80%;  
        width: 80% !important;
    }
  }

So you will target the .ui-dialog class since jQuery-UI adds a bunch of markup to the DOM and I'm putting the !important rule to force the override. Do not add the dialog width when you call the widget, let the CSS handle that.

$("#dialog").dialog();

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

For older browsers fallback check this repo on github and do a window search for media queries: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-browser-Polyfills

Implementing polyfill are usually pretty straightforward but that should be a different question in my opinion. Hope it helps.

Cheers