Zoom-on-rotate fix for WebKit mobile browsers
Join the DZone community and get the full member experience.
Join For Free
This blog post is a part of Mobilizing websites with responsive design and HTML5 tutorial. For all posts please see the Introduction post.
After adding meta viewport tag for your mobile site its width is properly formatted for mobile browsers. However, there exists a common glitch you should be aware of.
On iOS devices, and on some Android devices, the mobile browser re-zooms the web page when the device orientation changes. The browser applies heuristics and try to determine a new zoom level after the rotation, but sometimes the result is not desirable. When you rotate from the portrait mode to the landscape mode, the page zooms in too much.
In our case, the project client specifically requested to disable this little feature if possible, as it was irritating the test users on iPad devices.
This can be worked around by resetting the viewport with Javascript after the orientation changes.
An example code going into HTML <head> section:
<!-- Don't break scale on iPad rotate. By default iPad re-zooms the page when the device orientation changes. The heuristics here do not work always; our page got zoomed in though it should be max zoomed out. This snippet fixes the situation so that you can still zoom in, but when the device is rotated the scale is restored. --> <script type="text/javascript"> (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)); </script>
Please edit the scales part of the code for the desired min and max scaling level.
Note: Dynamic viewport manipulation is badly supported on older Android devices and contains many pitfalls.
1. More info
- [a class="reference external" href="http://webdesignerwall.com/tutorials/iphone-safari-viewport-scaling-bug"]http://webdesignerwall.com/tutorials/iphone-safari-viewport-scaling-bug
- http://adactio.com/journal/4470/
- http://stackoverflow.com/questions/2557801/how-do-i-reset-the-scale-zoom-of-a-web-app-on-an-orientation-change-on-the-iphon
Published at DZone with permission of Mikko Ohtamaa, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Decoding eBPF Observability: How eBPF Transforms Observability as We Know It
-
New ORM Framework for Kotlin
-
Observability Architecture: Financial Payments Introduction
-
DevOps in Legacy Systems
Comments