Skip to content

Instantly share code, notes, and snippets.

@keithchu
Forked from scottjehl/fixorientationzoom.js
Created January 6, 2012 00:49

Revisions

  1. Scott Jehl created this gist Jan 6, 2012.
    53 changes: 53 additions & 0 deletions fixorientationzoom.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    /*
    An attempt at fixing the dreaded iOS orientationchange zoom bug http://adactio.com/journal/5088/. Seems to work!
    Authored by @scottjehl
    MIT License.
    */

    (function(w){
    var doc = w.document;

    if( !doc.querySelectorAll ){ return; }

    var meta = doc.querySelectorAll( "meta[name=viewport]" )[ 0 ],
    initialContent = meta && meta.getAttribute( "content" ),
    disabledZoom = initialContent + ", maximum-scale=1.0",
    enabledZoom = initialContent + ", maximum-scale=10.0",
    enabled = true,
    orientation = w.orientation,
    rotation = 0;

    if( !meta ){ return; }

    function restoreZoom(){
    meta.setAttribute( "content", enabledZoom );
    document.body.innerHTML = document.body.innerHTML;
    enabled = true;
    }

    function disableZoom(){
    meta.setAttribute( "content", disabledZoom );
    enabled = false;
    }

    function checkTilt( e ){
    orientation = Math.abs( w.orientation );
    rotation = Math.abs( e.accelerationIncludingGravity.x );

    if( rotation > 8 && orientation === 0 ){
    if( enabled ){
    disableZoom();
    }
    }
    else {
    if( !enabled ){
    restoreZoom();
    }
    }

    }

    w.addEventListener( "orientationchange", restoreZoom, false );
    w.addEventListener( "devicemotion", checkTilt, false );

    })( this );