Quick and easy orientation detection for mobile sites
October 8th, 2010Here’s one of the quick tricks we’re talking about in the HTML5 Mobile Pro workshop.
If you want to react to change in orientation of the device on mobile sites, here’s a quick and easy to use snippet, that just sets a “horizontal” or “vertical” class on the body
element, so you can write some CSS to adapt your site:
document.body.onorientationchange = (function(){ document.body.className = orientation % 180 == 0 ? 'vertical' : 'horizontal'; return arguments.callee; })();
That’s it–stick this into a script
tag at the end of your page, just before the body
tag closes and you’re good.
This code will set a class of “horizontal” or “vertical” on the initial load page load, depending on the orientation of the device, and will also set the class whenever the orientation changes later.
Learn the gritty details on how this works, and much, much more at my HTML5 Mobile Pro workshop.
Tweet