I’ve been confounded by the iPhone/iPad’s inability to interpret the viewport meta tag. It’s something I’ve scratching my head over for the past couple of weeks. I remembered a few months ago I read Shi Chuan’s blog (one of the author’s of HTML5 Boilerplate) where he explained his fix for it. I found myself back at his blog today going over some old ground, and realised that his solution was a little trickier than the others I had been looking at.
Basically it changes the viewport meta tag with javascript after the document loads and then changes it again when the user gestures to allow user scaling. This lead me to Paul Irish’s solution that he wrote based on this work. It’s a good’en so I took it and implemented it. The only other problem is that the viewport moves when the orientation rotates – argh! But that’s cool, there is an event onorientationchange that can let me do stuff. So I added a document.body.scrollLeft = 0 to compensate for this behaviour and bingo!
I’ve refactored this script by turning the whole thing into an object (I’m big on that at the moment) so I can inject this into my plugins. It’s tested on iOS simulator and I’m happy with the result:
var ScaleFix = {
viewportmeta : document.querySelector && document.querySelector('meta[name="viewport"]'),
ua : navigator.userAgent,
gestureStart : function()
{
ScaleFix.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6";
},
init : function()
{
if (ScaleFix.viewportmeta && /iPhone|iPad/.test(ScaleFix.ua) && !/Opera Mini/.test(ScaleFix.ua))
{
ScaleFix.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0";
document.addEventListener("gesturestart", ScaleFix.gestureStart, false);
}
window.onorientationchange = function()
{
document.body.scrollLeft = 0;
};
}
};
ScaleFix.init();
That’s what I’m looking for!