Search code examples
javascriptcssmobile-safariviewport

Mobile site resize on orientation change not working in Safari


I'm new to mobile site development, so bear with me. Currently my site (http://farhillsanimalclinic.com/mobile) seems to be behaving in Android, but I'm having a problem in Safari. When I change from portrait to landscape orientation, everything resizes properly, but when switching from landscape to portrait, the elements are not being resized. I know that the resize function is getting called, because I temporarily added an alert to it, but it just seems not to be working properly. As I mentioned, it works well on an Android phone.

Here's the relevent code:

function getWidth() {
    xWidth = null;
    if(window.screen != null)
        xWidth = window.screen.availWidth;
    if(window.outerWidth != null)
        xWidth = window.outerWidth;
    return xWidth;
}

function getHeight() {
    xHeight = null;
    if(window.screen != null)
        xHeight = window.screen.availHeight;
    if(window.innerHeight != null)
        xHeight =   window.innerHeight;
    return xHeight;
}

function resizeWrapper() {
    xWidth = getWidth();
    xHeight = getHeight();
    $("#wrapper").css("width", xWidth + "px");
    $("#wrapper").css("min-height", xHeight + "px");
}

$(window).bind('orientationchange', resizeWrapper);
$(window).bind('resize', resizeWrapper);

If it matters, I'm using the following to define the viewport:

<meta name="viewport" content="target-densitydpi=device-dpi, initial-scale=1.0, minimum-scale=1.0, maximum-scale=2.0, user-scalable=1" />

Solution

  • It turned out to be a problem with Mobile Safari reporting window.outerWidth. After loading in portrait it correctly reported 320px, but after flipping from landscape to portrait (regardless of how the page was initially loaded) it never reported 320 again. Swapping to window.innerWidth seems to have done the trick; I just hope it doesn't introduce new problems I've not anticipated on other browsers.