Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created April 6, 2012 17:05
Show Gist options
  • Save jonathantneal/2321391 to your computer and use it in GitHub Desktop.
Save jonathantneal/2321391 to your computer and use it in GitHub Desktop.
iDevice Viewport Scaling
/iPad|iPhone/.test(navigator.platform) && (function (window, document) {
var
width = 'width', height = 'height',
// get <html>
documentElement = document.documentElement,
// get fake <head>
fakeHead = document.createElement('head'),
// get orientation
orientation = window.orientation % 180,
// get scaling
scalePortrait = screen[height] / screen[width],
scaleLandscape = screen[width] / screen[height],
// get resize event
resizeEvent = document.createEvent('HTMLEvents');
// set resize event
resizeEvent.initEvent('resize', true, false);
// set viewport
fakeHead.innerHTML = '<meta name="viewport" content="width=device-' + (orientation ? height : width) + '">';
documentElement.firstChild.appendChild(fakeHead.firstChild);
// set scaling defaults
documentElement.style.WebkitTextSizeAdjust = '100%';
documentElement.style.WebkitTransformOrigin = '0 0';
documentElement.style.WebkitTransition = '-webkit-transform 100ms';
// set orientation change event
window.addEventListener('orientationchange', function () {
// check new orientation
var newOrientation = window.orientation % 180;
// set scaling
document.documentElement.style.WebkitTransform = (newOrientation == orientation)
? 'scale(1)'
: 'scale(' + (orientation ? scalePortrait : scaleLandscape) + ')';
});
// set transition end event
window.addEventListener('webkitTransitionEnd', function (e) {
document.dispatchEvent(resizeEvent);
});
})(window, document);
@jonathantneal
Copy link
Author

This script min/gzip'd is 417 bytes.

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