Created
April 5, 2011 11:24
-
-
Save swervo/903435 to your computer and use it in GitHub Desktop.
Fixes iphone viewport scale bug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original code from http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/ | |
var metas = document.getElementsByTagName('meta'); | |
var i; | |
if (navigator.userAgent.match(/iPhone/i)) { | |
for (i=0; i<metas.length; i++) { | |
if (metas[i].name == "viewport") { | |
metas[i].content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0"; | |
} | |
} | |
document.getElementsByTagName('body')[0].addEventListener("gesturestart", gestureStart, false); | |
} | |
function gestureStart() { | |
for (i=0; i<metas.length; i++) { | |
if (metas[i].name == "viewport") { | |
metas[i].content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6"; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// My rewritten version | |
// 1) won't restrict viewport if JS is disabled | |
// 2) uses capture phase | |
// 3) assumes last viewport meta is the one to edit (incase for some odd reason there is more than one) | |
// 4) feature inference (no sniffs, behavior should be ignored on other enviros) | |
// 5) removes event handler after fired | |
!function(doc) { | |
var addEvent = 'addEventListener', | |
type = 'gesturestart', | |
qsa = 'querySelectorAll', | |
scales = [1, 1], | |
meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : []; | |
function fix() { | |
meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1]; | |
doc.removeEventListener(type, fix, !0); | |
} | |
if ((meta = meta[meta.length - 1]) && addEvent in doc) { | |
fix(); | |
scales = [.25, 1.6]; | |
doc[addEvent](type, fix, !0); | |
} | |
}(document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment