Created
April 30, 2012 08:08
-
-
Save jeremyworboys/2556435 to your computer and use it in GitHub Desktop.
Javascript: Fix iOS inappropriate zooming
This file contains hidden or 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
/*! A fix for the iOS orientationchange zoom bug. | |
Script by @scottjehl, rebound by @wilto. | |
MIT License. | |
*/ | |
(function(w){ | |
// This fix addresses an iOS bug, so return early if the UA claims it's something else. | |
if( !( /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1 ) ){ | |
return; | |
} | |
var doc = w.document; | |
if( !doc.querySelector ){ return; } | |
var meta = doc.querySelector( "meta[name=viewport]" ), | |
initialContent = meta && meta.getAttribute( "content" ), | |
disabledZoom = initialContent + ",maximum-scale=1", | |
enabledZoom = initialContent + ",maximum-scale=10", | |
enabled = true, | |
x, y, z, aig; | |
if( !meta ){ return; } | |
function restoreZoom(){ | |
meta.setAttribute( "content", enabledZoom ); | |
enabled = true; | |
} | |
function disableZoom(){ | |
meta.setAttribute( "content", disabledZoom ); | |
enabled = false; | |
} | |
function checkTilt( e ){ | |
aig = e.accelerationIncludingGravity; | |
x = Math.abs( aig.x ); | |
y = Math.abs( aig.y ); | |
z = Math.abs( aig.z ); | |
// If portrait orientation and in one of the danger zones | |
if( !w.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ){ | |
if( enabled ){ | |
disableZoom(); | |
} | |
} | |
else if( !enabled ){ | |
restoreZoom(); | |
} | |
} | |
w.addEventListener( "orientationchange", restoreZoom, false ); | |
w.addEventListener( "devicemotion", checkTilt, false ); | |
})( this ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment