Getting Started with Device Orientation Events

When you want more information than just the screen portrait or landscape orientation, it’s time to dive into the deviceorientation event, which gives you three angular values indicating precisely how the device is held in 3-D space and is triggered at a high rate as the device is adjusted.

The specification associated with device orientation is the DeviceOrientation Event Specification; the latest version is available at: www.w3.org/TR/orientation-event/. The most important event is deviceorientation, which you can use to determine the angle at which you are holding your device.

Although this event is useful in mobile devices, desktop browsers have also started supporting the event (MacBooks started including an accelerometer a couple of years ago), and it’s available in Chrome. Firefox also has support for it, but at least in OS X, Firefox doesn’t trigger the event. Desktop IE, Safari, and Opera don’t have support as of this writing.

Detecting and Using the Event

To see if your browser supports the event, you can check for the existence of the event object on the window:

  if (window.DeviceOrientationEvent) {
      // Device orientation supported
  }

Firefox pre-version 6 had support for a nonstandard OrientationEvent, but since version 6 it has supported the standard event.

Next, to listen for the event, as usual you can either use addEventListener or jQuery. The only caveat is that if you use jQuery you need to pull out the original event ...

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.