Automatically change width and height using jQuery dialog

I am using jQuery UI dialog to load ajax content. It correctly positions the dialog vertically, however with the option width: "auto" it does not center it horizontally. It is not centered, like 100px to the right of the center.

Here is my code:

 $('.open').live('click', function(e) { e.preventDefault(); $("#modal").load($(this).attr('href')).dialog({ title: $(this).attr('title'), modal: true, autoOpen: true, draggable: false, resizable: false, width: 'auto', position: ['center', 'top'] }); }); 

Any ideas if there is a way to automatically resize and save in the center?

EDIT: This works:

 $("#modal").load($(this).attr('href'), function() { $("#modal").dialog({ title: $(this).attr('title'), width: 'auto', modal: true, autoOpen: true, draggable: false, resizable: false, position: ['center', 150], create: function(event, ui) {} }); }); 
+6
source share
2 answers

To avoid positioning problems, you should wait for the content to load before creating or opening a dialog. Otherwise:

  • The jQuery UI dialog will calculate the width and center of an empty div
  • When the content is loaded, the right side of the dialog is stretched to fit the content, while the left side remains fixed, causing the dialog to shift to the right.

Your sample code should be modified as follows:

 $("#modal").load("/ajax/content.html", function() { // callback is executed after post-processing and HTML insertion has been performed // this refers to the element on which load method was called $(this).dialog({ modal: true, autoOpen: true, draggable: false, resizable: false, width: "auto", position: { my: "top", at: "top", of: window } }); }); 
+2
source

Try this code. It works for me and is a cross browser.

 $(window).resize(function(){ $('.className').css({position:'absolute', left:($(window).width() - $('.className').outerWidth())/2, top: ($(window).height() - $('.className').outerHeight())/2 }); }); // To initially run the function: $(window).resize(); 

Creating a dialogue from this should be fairly simple.

0
source

Source: https://habr.com/ru/post/905996/


All Articles