Thursday, August 19, 2010

Detecting orientation change of mobile devices

Couple of weeks ago I was asked by one of the biggest online games company to adapt several of my games for their new portal designed for mobile devices.
One of the most important thing in this venture was to disable orientation changing of the phone. Simplest way to check if it is in landscape or in portrait mode (in every device, because I know there are functions dedicated for Iphone and maybe some for Android also) is to check if height of the screen is bigger or lower than it's width.

function checkOrientation() {
if (window.innerHeight > window.innerWidth) {
//portrait mode
} else if(window.innerHeight< window.innerWidth) { //landscape mode
}
}
It's not possible to guess in which mode user enters the page (game in that case) so it's important to check it in the begging, and each time the browser's window resize.

checkOrientation();
window.onresize = function() { //your code
checkOrientation();
}
Try this link from your phone to test it, or just open it in desktop browser and change window size: LANDSCAPE VS PORTRAIT
I know it won't works in IE, but almost all of the mobile web browsers are based on WebKit.

8 comments:

  1. Mobile devices with internet access are becoming increasingly popular. This topic section on mobile devices for business includes resources and tips for selecting and maintaining all types of mobile devices such as smartphones, cell phones, netbooks and laptops for your business users. Thanks.

    ReplyDelete
  2. This method is very good, I test once, use is also very simple, thank you for sharing.

    ReplyDelete
  3. There is a problem with this method.. when virtual keyboard is visible in portrait mode, checkOrientation function will return landscape.

    ReplyDelete
  4. I was very pleased to find this site. I wanted to thank you for this great read!! I definitely enjoyed every little bit of it and I have you bookmarked to check out the new stuff you post. cell phone detector

    ReplyDelete
  5. Good work you have done and shared with us.

    ReplyDelete
  6. This article offers clear idea in favor of the new users of blogging, that in fact

    ReplyDelete