Tuesday, January 17, 2012

JQuery UI Dialog Auto Width and Height Cross Browser (Fixed IE issue)

JQuery Dialog is one of my most used UI components.  However, the width: 'auto'; and height: 'auto'; options are not supported in IE, which means if you set them to 'auto', the dialog will expand to take the full window width and height will be undetermined.
I have searched around the web and see many people having the same issue but no solutions. Luckily, I was able to find a way to make it work.  Here is how:

1. Create a wrapper element (i.e. div) around your dialog content.

....Actual Dialog Contents....

2. Add the following style on the page

This is the key part. IE does not calculate the actual width if you don't specify a width value initially, it will use the browser window width instead. By giving IE an initial width value, it will set it to the proper value. The IE check here is necessary, because this should only be applied to IE. If you do not do IE check, FF and Chrome will use the width and height value as the result dialog width and heigth.

3. Finally, add the following javascript code on the page.

   //Get the acutal width and height and add some margin
   var w = $("#my_dialog #wrapper")[0].clientWidth + 20;
   var h = $("#my_dialog #wrapper")[0].clientHeight + 20; 
   $("#my_dialog").dialog('option', {'width':w,'height':h});
This piece of code will find the actual width and height and update the dialog to the current width and height.

Let me know if you encounter any issue with this solution. :)