Looking at a Device Orientation

Before examining the DeviceOrientation Event API, it’s worth a brief look at the window.orientation property. This property won’t tell you the exact angle you hold your device at, but it can tell you an angle that indicates which way—portrait or landscape—your device’s screen is oriented.

You can also listen for orientationchange events to detect when the device is rotated to a different configuration. To try this, add the following to any page that has jQuery loaded on it:

    $(window).on("orientationchange",function(e) {
      alert(window.orientation);
    });

Depending on your device, as you rotate your device every time the screen rotates, you should see values in increments of 90 that tell you what angle the device is at. Although it seems like it should be easy to decode this value, it’s not that simple.

Phones, specifically the iPhone and the Galaxy Nexus, treat the normal portrait position as a window.orientation value of 0. Neither supports an upside-down portrait, so there is no 180 value. The iPhone has two landscape orientations: 90 and –90, whereas the Galaxy Nexus treats landscape direction as having a window.orientation of 90.

For tablets it’s more confusing. The Kindle Fire and iPad both treat normal portrait mode as having an orientation of 0, but they also support an inverted portrait mode with an orientation of 180 that is not supported on phones. Other tablets, such as the Android ASUS Transformer, treat landscape mode as an orientation ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.