[javascript] Automatically resize jQuery UI dialog to the width of the content loaded by ajax

I'm having a lot of trouble finding specific information and examples on this. I've got a number of jQuery UI dialogs in my application attached to divs that are loaded with .ajax() calls. They all use the same setup call:

 $(".mydialog").dialog({
        autoOpen: false,
        resizable: false,
        modal: true
 });

I just want to have the dialog resize to the width of the content that gets loaded. Right now, the width just stays at 300px (the default) and I get a horizontal scrollbar.

As far as I can tell, "autoResize" is no longer an option for dialogs, and nothing happens when I specify it.

I'm trying to not write a separate function for each dialog, so .dialog("option", "width", "500") is not really an option, as each dialog is going to have a different width.

Specifying width: 'auto' for the dialog options just makes the dialogs take up 100% of the width of the browser window.

What are my options? I'm using jQuery 1.4.1 with jQuery UI 1.8rc1. It seems like this should be something that is really easy.

EDIT: I've implemented a kludgy workaround for this, but I'm still looking for a better solution.

This question is related to javascript jquery ajax jquery-ui jquery-ui-dialog

The answer is


For some reason I kept having this full page width problem with IE7 so I made this hack:

var tag = $("<div></div>");
//IE7 workaround
var w;
if (navigator.appVersion.indexOf("MSIE 7.") != -1)
    w = 400;
else
    w = "auto";

tag.html('My message').dialog({
    width: w,
    maxWidth: 600,
    ...

Here's how I did it:

Responsive jQuery UI Dialog ( and a fix for maxWidth bug )

Fixing the maxWidth & width: auto bug.


Had the same problem and thanks to you mentioning that the real problem was related to CSS I found the issue:

Having position:relative instead of position:absolute in your .ui-dialog CSS rule makes the dialog and width:'auto' behave strangely.

.ui-dialog { position: absolute;}

I had the same problem when I upgraded jquery UI to 1.8.1 without upgrading the corresponding theme. Only is needed to upgrade the theme too and "auto" works again.


You can avoid the 100% width issue by specifying a maximum width. The maxWidth option does not seem to work; so set the CSS max-width property on the dialog widget instead.

In case you also want to constrain the maximum height, use the maxHeight option. It will correctly show a scrollbar when necessary.

_x000D_
_x000D_
$(function() {_x000D_
  var $dialog = $("#dialog");_x000D_
  $dialog.dialog({_x000D_
    autoOpen: false,_x000D_
    modal: true,_x000D_
    width: "auto"_x000D_
  });_x000D_
  /*_x000D_
   * max-width should be set on dialog widget because maxWidth option has known issues_x000D_
   * max-height should be set using maxHeight option_x000D_
   */_x000D_
  $dialog.dialog("widget").css("max-width", $(window).width() - 100);_x000D_
  $dialog.dialog("option", "maxHeight", $(window).height() - 100);_x000D_
  $(".test-link").on("click", function(e) {_x000D_
    e.preventDefault();_x000D_
    $dialog.html($(this.hash).html());_x000D_
    // if you change the content of dialog after it is created then reset the left_x000D_
    // coordinate otherwise content only grows up to the right edge of screen_x000D_
    $dialog.dialog("widget").css({ left: 0 });_x000D_
    $dialog.dialog("open");_x000D_
  });_x000D_
});
_x000D_
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>_x000D_
_x000D_
<div id="dialog"></div>_x000D_
_x000D_
<!-- test links -->_x000D_
_x000D_
<p>_x000D_
  <a href="#content-1" class="test-link">Image (Landscape)</a>_x000D_
  <a href="#content-2" class="test-link">Image (Portrait)</a>_x000D_
  <a href="#content-3" class="test-link">Text Content (Small)</a>_x000D_
  <a href="#content-4" class="test-link">Text Content (Large)</a>_x000D_
</p>_x000D_
<p>If you are viewing in Stack Snippets > Full page then reload the snippet so that window height is recalculated (Right click > Reload frame).</p>_x000D_
_x000D_
<!-- sample content -->_x000D_
_x000D_
<div id="content-1" style="display: none;">_x000D_
  <img src="https://i.stack.imgur.com/5leq2.jpg" width="450" height="300">_x000D_
</div>_x000D_
_x000D_
<div id="content-2" style="display: none;">_x000D_
  <img src="https://i.stack.imgur.com/9pVkn.jpg" width="300" height="400">_x000D_
</div>_x000D_
_x000D_
<div id="content-3" style="display: none;">_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sodales eu urna sit amet fermentum. Morbi ornare, leo ut ornare volutpat, nibh diam mattis elit, eget porta sapien quam eu mi. Nullam sollicitudin, nibh non suscipit commodo, nisi metus bibendum urna, vitae congue nisl risus eu tellus. Praesent diam ligula, hendrerit eget bibendum quis, convallis eu erat. Aliquam scelerisque turpis augue, sit amet dictum urna hendrerit id. Vestibulum luctus dolor quis ex sodales, nec aliquet lacus elementum. Mauris sollicitudin dictum augue eget posuere. Suspendisse diam elit, scelerisque eu quam vel, tempus sodales metus. Morbi et vehicula elit. In sit amet bibendum mi.</p>_x000D_
</div>_x000D_
_x000D_
<div id="content-4" style="display: none;">_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sodales eu urna sit amet fermentum. Morbi ornare, leo ut ornare volutpat, nibh diam mattis elit, eget porta sapien quam eu mi. Nullam sollicitudin, nibh non suscipit commodo, nisi metus bibendum urna, vitae congue nisl risus eu tellus. Praesent diam ligula, hendrerit eget bibendum quis, convallis eu erat. Aliquam scelerisque turpis augue, sit amet dictum urna hendrerit id. Vestibulum luctus dolor quis ex sodales, nec aliquet lacus elementum. Mauris sollicitudin dictum augue eget posuere. Suspendisse diam elit, scelerisque eu quam vel, tempus sodales metus. Morbi et vehicula elit. In sit amet bibendum mi.</p>_x000D_
  <p>Aenean eu magna tempor, pellentesque arcu eget, mattis enim. Cras at volutpat mi. Aenean id placerat felis, quis imperdiet nunc. Aenean a iaculis est, quis lacinia nisl. Sed aliquet sem eget justo convallis congue. Quisque rhoncus nulla sit amet cursus maximus. Phasellus nec auctor urna. Nam mattis felis et diam finibus consectetur. Etiam finibus dignissim vestibulum. In eu urna mattis dui pharetra iaculis. Nam eleifend odio et massa imperdiet, et hendrerit mauris tempor. Quisque sapien lorem, dapibus ut ultricies ut, hendrerit in nulla. Nunc lobortis mi libero, nec tincidunt lacus pretium at. Aliquam erat volutpat.</p>_x000D_
  <p>Fusce eleifend enim nec massa porttitor tempor a eget neque. Quisque vel augue ac urna posuere iaculis. Morbi pharetra augue ac interdum pulvinar. Duis vel posuere risus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut vitae lectus non nisl iaculis volutpat nec vitae ante. Maecenas quis condimentum elit. Sed nisl urna, convallis ut pellentesque sit amet, pellentesque eget quam. Pellentesque ornare sapien ac scelerisque pretium. Pellentesque metus tortor, accumsan in vehicula iaculis, efficitur eget nisi. Donec tincidunt, felis vel viverra convallis, lectus lectus elementum magna, faucibus viverra risus nulla in dolor.</p>_x000D_
  <p>Duis tristique sapien ut commodo laoreet. In vel sapien dui. Vestibulum non bibendum erat. Etiam iaculis vehicula accumsan. Phasellus finibus, elit et molestie luctus, massa arcu tempor nulla, id hendrerit metus mauris non mi. Morbi a ultricies magna. Proin condimentum suscipit urna eu maximus. Mauris condimentum massa ac egestas fermentum. Praesent faucibus a neque a molestie. Integer sed diam at eros accumsan convallis.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


I have the same problem and having position: absolute in your .ui-dialog{} css was not enough. I noticed that position: relative was being set on the actual element's direct style, so the .ui-dialog css definition was getting overwritten. Setting position: absolute on the div I was going to make a dialog statically also did not work.

In the end I changed two placed in my local jQuery to make this work.

I changed the following line in jQuery to be:

elem.style.position = "absolute";

at https://github.com/jquery/jquery/blob/1.8.0/src/offset.js#L62

Also, since my dialog was set to draggable, I had to change this line as well in jQuery-ui to be:

this.element[0].style.position = 'absolute';

at https://github.com/jquery/jquery-ui/blob/1-8-stable/ui/jquery.ui.draggable.js#L48

Perhaps going through the style I have more thoroughly would fix things, but thought I'd share how I got this working.


I had a similar problem.

Setting width to "auto" worked fine for me but when the dialog contained a lot of text it made it span the full width of the page, ignoring the maxWidth setting.

Setting maxWidth on create works fine though:

$( ".selector" ).dialog({
  width: "auto",
  // maxWidth: 660, // This won't work
  create: function( event, ui ) {
    // Set maxWidth
    $(this).css("maxWidth", "660px");
  }
});

All you need to do is just to add:

width: '65%',

Adding to Vladimir Kornea's answer.

I wanted a way to set the width unless the screen was too small, then a dynamic width. Not truly "responsive" bit works well for most cases.

, 'open': function(){
   var resposive_width = ($( window ).width() > 640) ? 640 : ($( window ).width() - 20);
   $(this).dialog('option', 'width', resposive_width)
 }

I had this problem as well.

I got it working with this:

.ui-dialog{
    display:inline-block;
}

edit this bellow:

_x000D_
_x000D_
$("#message").dialog({_x000D_
 autoOpen:false,_x000D_
 modal:true,_x000D_
 resizable: false,_x000D_
 width:'80%',
_x000D_
_x000D_
_x000D_


If you need it to work in IE7, you can't use the undocumented, buggy, and unsupported {'width':'auto'} option. Instead, add the following to your .dialog():

'open': function(){ $(this).dialog('option', 'width', this.scrollWidth) }

Whether .scrollWidth includes the right-side padding depends on the browser (Firefox differs from Chrome), so you can either add a subjective "good enough" number of pixels to .scrollWidth, or replace it with your own width-calculation function.

You might want to include width: 0 among your .dialog() options, since this method will never decrease the width, only increase it.

Tested to work in IE7, IE8, IE9, IE10, IE11, Firefox 30, Chrome 35, and Opera 22.


I imagine setting float:left for the dialog will work. Presumably the dialog is absolutely positioned by the plugin, in which case its position will be determined by this, but the side-effect of float - making elements only as wide as they need to be to hold content - will still take effect.

This should work if you just put a rule like

.myDialog {float:left}

in your stylesheet, though you may need to set it using jQuery


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete

Examples related to jquery-ui-dialog

Error: TypeError: $(...).dialog is not a function jQuery UI Dialog - missing close icon jquery ui Dialog: cannot call methods on dialog prior to initialization jQuery dialog popup jQuery UI Alert Dialog as a replacement for alert() How to display an IFRAME inside a jQuery UI dialog How can I disable a button on a jQuery UI dialog? Detect if a jQuery UI dialog box is open How to close jQuery Dialog within the dialog? How to completely remove a dialog on close