Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mathiasbynens/901295 to your computer and use it in GitHub Desktop.
Save mathiasbynens/901295 to your computer and use it in GitHub Desktop.
Improved version of JavaScript fix for the iOS viewport scaling bug. See http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/
// 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";
}
}
}
// Rewritten version
// By @mathias, @cheeaun and @jdalton
(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, true);
}
if ((meta = meta[meta.length - 1]) && addEvent in doc) {
fix();
scales = [.25, 1.6];
doc[addEvent](type, fix, true);
}
}(document));
@jpblancoder
Copy link

You might want to update with additional meta params, for iOS 6+.

function fix() {
        meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=' + scales[1] + ', user-scalable=no, minimum-scale=' + scales[0];
        doc.removeEventListener(type, fix, true);
    }

@DaveFlash
Copy link

hmm, still seems to create problems for me....

@HarroH
Copy link

HarroH commented Aug 11, 2017

Is this fix still applicable to iOS or has Apple solved this issue?

@webaffin
Copy link

Is this fix still applicable to iOS or has Apple solved this issue?

I also want to know...

@GraniteConsultingReviews

I tested this code and its working well. thanks for sharing.

@MattShaile
Copy link

I don't think this works any more (iOS 10+) due to Apple now ignoring the scale meta tags

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment