Auto resize width and height with jQuery dialog
Asked Answered
O

2

7

I am using jQuery UI dialog to load ajax content. It is correctly positions the dialog vertically, however, with width: "auto" option it does not center it horizontally. It is off-centered, like 100px to the right of 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's a way to have it auto resize and remain centered?

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) {}
    });
});
Outmaneuver answered 14/1, 2012 at 21:56 Comment(5)
add css margin-left:auto;margin-right:auto; to your object to set it center, do it.Immitigable
jquery resizes it, it will override any default stylesOutmaneuver
after create it, I'm sleepy and i cant find it, sorry :D, but when your object insert in your page you can change its position.Immitigable
possible duplicate of Centering jQuery UI dialog of unknown height - is it possible?Alake
Maybe you should anwser your own question + accept that...Wylde
D
3

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

  1. jQuery UI dialog will calculate the width and center of the empty div
  2. When the content loads, the right side of the dialog stretches to accomodate the content while the left side remains fixed, causing the dialog to appear shifted towards right

Your sample code should be changed to this:

$("#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 }
  });
});
Darmstadt answered 5/5, 2015 at 11:19 Comment(0)
O
0

Try this code. It works for me and is 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 dialog from this is should be fairly straight forward.

Offset answered 31/3, 2015 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.