Handle Device Orientation

Device orientation data is available to your app through JavaScript on devices that support the ondeviceorientation property of the window object. The W3C provides a DeviceOrientation Event Specification that describes how to access device orientation data.

Detect Whether Device Orientation is Supported

To detect whether device orientation is supported, check to see whether the ondeviceorientation property is present in the window object. If it is present, device orientation is supported. Once you have checked to ensure device orientation is a supported property, add a listener for device orientation events to the window, and assign a handler.

if ("ondeviceorientation" in window) {
  // device orientation is supported
  // add an event listener for device orientation events and assign a handler
  window.addEventListener("deviceorientation", deviceOrientationEventHandler);
} else {
  // device orientation is not supported
}

Handle Device Orientation Events

The handler function receives device orientation event data, which consists of the following properties:

  • alpha (double) is the degree of rotation around the Z axis, ranging from [0, 360).
  • beta (double) is the degree of rotation around the X axis, ranging from [–180, 180).
  • gamma (double) is the degree of rotation around the Y axis, ranging from [–90, 90).
  • absolute (boolean) is true when the values for the three angles are relative to the Earth's coordinate frame.

An example handler function is shown here:

function deviceOrientationEventHandler(deviceOrientationData) {
  var alpha = deviceOrientationData.alpha;
  var beta = deviceOrientationData.beta;
  var gamma = deviceOrientationData.gamma;
  var absolute = deviceOrientationData.absolute;

  console.log("Alpha: " + alpha + " Beta: " + beta + " Gamma: " + gamma + " Absolute: " + absolute);
}

In the DeviceOrientation sample, numerical device orientation information is displayed above a bubble level that shows a visual representation of the same data. To display this data, a variable called orientation is created to keep track of the device's screen orientation (portrait or landscape). Once the screen orientation is known, math is applied to normalize the beta and gamma measurements.

Note that the normalization performed in the example is a simple transform, not a full polar normalization. Once the data is normalized, the displayed numerical values are updated, and the position of the bubble in the bubble level is also updated.