Search code examples
jquerydialogpopuppositioncenter

Center jQuery popUp dialog with auto width and auto height


I have following initialization of jQuery popUp dialog, with dynamic content :

  jQuery("#popUp").live("click", function (e) {
   e.preventDefault();
    jQuery("<div></div>")
        .addClass("dialog")
        .attr("id", "popUpDialog")
        .appendTo("body")
        .dialog({
            title: jQuery(this).attr("data-dialog-title"),
            close: function() { jQuery(this).remove(); },
            modal: true,
            hide: { effect: "none", duration: 150 },
            show: { effect: "none", duration: 150 },
            width: 'auto',
            height: 'auto',
            position: {
                my: 'center',
                at: 'center',
            of: jQuery(window)
            }
        }).load(this.href);

    jQuery(".close").live("click", function (e) {
        e.preventDefault();
        jQuery(this).closest(".dialog").dialog("close");
    });
});

});

I am sorry for this simplest question , but I can not place the popUp window on center of the whole page . The problem is in :

                  position: {
                  my: 'center',
                  at: 'center',
              of: jQuery(window)}

Solution

  • The issue is because the dialog is being positioned before its content is loaded, and therefore it's size is changing. Change your logic so that the content is loaded first, and then instantiate the dialog:

    $('<div />', {
      class: 'dialog',
      id: 'popUpDialog' 
    }).appendTo('body').load(this.href, function() {
      // set up the dialog in the callback of the AJAX request...
      $(this).dialog({
        title: jQuery(this).attr("data-dialog-title"),
        close: function() { jQuery(this).remove(); },
        modal: true,
        hide: { effect: "none", duration: 150 },
        show: { effect: "none", duration: 150 },
        width: 'auto',
        height: 'auto',
        position: {
          my: 'center',
          at: 'center',
          of: window
        }
      })
    });