Platform-Independent Zoomable Screen Detection

posted on Wednesday, June 17, 2009 at 7:37 AM PDT by Slippy Douglas | 2 comments

Problem

You want your website’s liquid/flexible-width or more-narrow-than-normal fixed-width layout to use a smaller width on mobile platforms with zoomable bowsers (i.e. iPhone OS, Android, WebOS).

Typical Solution

Check the user-agent string (server-side or with JavaScript) for one of the pre-existing zoomable browsers and enforce the width.

Flaws

It will break for any browser (past, present, or future) that you didn’t account for. It will probably break if a future device has a screen sizeIt may break if somehow, the user-agent check matches a non-zoomable browser.

Better Solution

Check if the rendered page’s width is larger than the browser window’s width. Also check if the browser’s screen width is less than the minimum width that your site needs in order to render correctly. If both of these are true, insert the necessary <meta name="viewport" .../> tag.

Implementation

Include this snippet in a JavaScript file that’s referenced between the <head> tags:

// Platform-Independent Zoomable Screen Detection
// Copyright 2009 Slippy Douglas.
// No rights reserved other than making sure this is free to use, modify, redistribute, whatever for forever and ever.
// set the minimum width your site needs to render properly here
var kPageMinWidth = 320;

function writePageMinWidthAdjustment() {
        // if the screen's width is smaller than the page's width
        // (i.e. a zoomable mobile device like the iPhone)
        if (window.screen.width < window.innerWidth) {
                // set the meta-data to the larger of the device's width or the minimum the site needs
                newWidth = Math.max(kPageMinWidth, window.screen.width);
                
                // will write the meta tag right into the <head/>
                document.write('<meta name="viewport" content="width=' + newWidth + '"/>');
        }
}

writePageMinWidthAdjustment();

And voila! Mobile browsers use the correct width. Enjoy.

Comments

Hamlet D'Arcy said on Wednesday, June 17, 2009:

This should really be licensed under the WTFPL: http://sam.zoy.org/wtfpl/

Slippy Douglas said on Friday, June 19, 2009:

Nice. I may have to switch over to that… or take advantage of their clause where you can modify the license WTF way you want to (as long as you call it something different).

Post a comment


(required, but not displayed)

(optional, and awesome)

(required)