iOS orientation change zoom bug fix


/ Published in: JavaScript
Save to your folder(s)

This is a simple fix for the iOS zoom bug that happens when changing screen orientations.


Copy this code and paste it in your HTML
  1. /*! A fix for the iOS orientationchange zoom bug.
  2.  Script by @scottjehl, rebound by @wilto.
  3.  MIT License.
  4. */
  5. (function(w){
  6. // This fix addresses an iOS bug, so return early if the UA claims it's something else.
  7. if( !( /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1 ) ){ return; }
  8. var doc = w.document;
  9. if( !doc.querySelector ){ return; }
  10. var meta = doc.querySelector( "meta[name=viewport]" ),
  11. initialContent = meta && meta.getAttribute( "content" ),
  12. disabledZoom = initialContent + ",maximum-scale=1",
  13. enabledZoom = initialContent + ",maximum-scale=10",
  14. enabled = true,
  15. x, y, z, aig;
  16. if( !meta ){ return; }
  17. function restoreZoom(){
  18. meta.setAttribute( "content", enabledZoom );
  19. enabled = true; }
  20. function disableZoom(){
  21. meta.setAttribute( "content", disabledZoom );
  22. enabled = false; }
  23. function checkTilt( e ){
  24. aig = e.accelerationIncludingGravity;
  25. x = Math.abs( aig.x );
  26. y = Math.abs( aig.y );
  27. z = Math.abs( aig.z );
  28. // If portrait orientation and in one of the danger zones
  29. if( !w.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ){
  30. if( enabled ){ disableZoom(); } }
  31. else if( !enabled ){ restoreZoom(); } }
  32. w.addEventListener( "orientationchange", restoreZoom, false );
  33. w.addEventListener( "devicemotion", checkTilt, false );
  34. })( this );

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.