JavaScript – How to Find Virtual Viewport/Screen Width

androidjavascriptmobilemobile-safari

Is there a consistent way to determine the width of the screen and virtual viewport for mobile devices using Javascript? My target platforms are mobile Safari and Android's stock browser, but I'm also testing with other browsers on Android.

I've tried with screen.width, window.innerWidth, document.getElementByTagName("body")[0].clientWidth, and jQuery's $(window).width().

Mobile Safari (from ios 3.1.3(7E18), original iPod touch) shows useful values, but the stock Android browser (Android 2.3.7) doesn't.

Ideally, I think that screen.width should show the actual pixel resolution of the screen: 320px on the iPod Touch and 480px on the Samsung Galaxy S2. Based on what I've been reading, one of the other numbers should show the width of the layout viewport which should be 980px on the iTouch and 800px on the Samsung Galaxy S2.
.
.

Code

<body>
<h1>screen.width: <span id="screen_width"></span></h1>
<h1>window.innerwidth: <span id="window_innerwidth"></span></h1>
<h1>clientWidth: <span id="clientwidth"></span></h1>
<h1>jQuery width: <span id="jquery_width"></span></h1>
</body>

<script type="text/javascript" src="jquery/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
    window.onload = function(){
        var swidth = screen.width;
        var wiwidth = window.innerWidth;
        var cwidth = document.getElementsByTagName("body")[0].clientWidth;
        var jwidth = $(window).width();
        document.getElementById("screen_width").innerHTML = swidth;
        document.getElementById("window_innerwidth").innerHTML = wiwidth;
        document.getElementById("clientwidth").innerHTML = cwidth;
        document.getElementById("jquery_width").innerHTML = jwidth;
    }
</script>

.
.

Results

iOS Safari:
screen.width: 320
window.innerwidth: 980
clientWidth: 964
jQuery width: 980

Android Browser:
screen.width: 800
window.innerWidth: 800
clientWidth: 784
jQuery width: 800

Firefox Mobile (a.k.a. Fennec):
screen.width: 480
window.innerwidth: 980
clientWidth: 964
jQuery width: 980

The Safari results are certainly useable, but not the Android Browser's results.

It's ironic that the Firefox mobile results are accurate. Although it provides a nice browsing experience from a user perspective, it's not a big enough target for mobile devices and there are many other things that don't work well on this browser.

Best Answer

Another StackOverflow question has this as a workaround:

setTimeout(YourFunction, 200);

And if you want the details, you can read about the bug in the issue tracker. You're experiencing a bug that exists in Android 2.2 and 2.3.

Related Question