Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Mobile Popup not centered on first click

I have a confusing problem with centering a jQuery Mobile popup. When I click it the first time it is not centered and appears in the corner of my page. After closing it and opening it again it is suddenly centered.

This is my code:

$(document).on("pageshow",function(){
  $('.image_link').on('click', function(event){
    var id = $(this).children('img').attr("id");
    $("#show_image_img").attr("src",sPath + "/view/images/" + id);
    $("#show_image").popup('open');
    $("#show_image" ).popup({ positionTo: "window" });
  });
});

and this is my html code

<div data-role="popup" id="show_image" data-theme="c" class="ui-corner-all">
  <div style="padding:20px 30px;">
    <img id="show_image_img" src="" />
  </div>
</div>

Does anybody have an idea how to solve this problem? I tried already various things like changing the pageshow event to a pagebeforeshow and so on.

like image 362
J-H Avatar asked Dec 04 '22 07:12

J-H


2 Answers

I believe on first click the popup is loading before the image is completely downloaded, so it does not know the size to use for positioning. Therefore, the top-left corner is centered.

If you know the image size ahead of time, you could pre-size the IMG tag in the popup via CSS

If you don't have too many images on the page, you could try pre-loading them

You could also add a small setTimeout delay on the popup to allow the image download to complete:

$(document).on("pageshow", function () {
    $('.image_link').on('click', function (event) {
        $("#show_image_img").attr("src", "http://www.aai.ee/planets/nineplanets/gif/SmallWorlds.jpg");

        setTimeout(OpenPopup, 50);
    });
});

function OpenPopup(){
    $("#show_image").popup({ positionTo: "window" }).popup('open');
}
like image 162
ezanker Avatar answered Jan 22 '23 19:01

ezanker


You can reposition the popup after the image is loaded :

$(document).on("pageshow", function () {
    $('.image_link').on('click', function (event) {
        var $img=$("#show_image_img").attr("src", "http://www.thinkstockphotos.com/CMS/StaticContent/WhyThinkstockImages/Best_Images.jpg");
        var $popup=$("#show_image").popup("open", {
            "positionTo": "window"
        });
        $img.one('load',function(){
            $popup.popup("reposition", {
                "positionTo": "window"
            });
        });
    });
});

edit: added the positionto window at the popup opening because if the image is not loaded (dead link for example) then the popup was not centered.

like image 25
QuickFix Avatar answered Jan 22 '23 19:01

QuickFix