samccone
samccone

Reputation: 10926

How to get the correct android available screen height of the browser in javascript

I am working on a mobile app and I need to get the correct browser inner height for it.

I am currently using

$(window).height()

to calculate the height. this works fine on the iphone/ipad

When I booted up a Galaxy S2 running android 2.3.5

I started to get some strange results...

The first time the page loads and $(window).height() is called on

$().ready(function(){...

I get the correct results (regardless of the phone being vertical or horizontal)

As soon as I rotate the phone into a horizontal position it reports back the correct height

the issue happens when rotating the phone from horizontal to vertical

The Phone reports back a completely incorrect height value

Now I tried using these values to see if any of the values were correct

screen.height   
screen.availHeight  

but still the same results


I am using this method to detect rotation

    var previousOrientation = 0;
var checkOrientation = function(){
    if(window.orientation !== previousOrientation){
        previousOrientation = window.orientation;
        // orientation changed, do your magic here
    }
};

window.addEventListener("resize", checkOrientation, false);
window.addEventListener("orientationchange", checkOrientation, false);

// (optional) Android doesn't always fire orientationChange on 180 degree turns
setInterval(checkOrientation, 2000);

Upvotes: 3

Views: 7072

Answers (1)

gregers
gregers

Reputation: 13040

Screen size and innerHeight in the Android browser is really f.u.b.a.r. Especially in combination with a bug that sometimes cause the WebView not to resize when closing the keyboard. The most sane property I've found for Android is window.outerHeight. On Android it usually reports screen height minus status bar height. Doesn't do the same on iOS though, so you might need to do some browser sniffing ;(

Upvotes: 7

Related Questions