Device orientation

Device orientation

The device orientation event returns rotation data, which includes how much the device is leaning front-to-back, side-to-side and if the phone or laptop has a compass, the direction the device is facing.

TL;DR

  • Use sparingly
  • Test for support
  • Don't update the UI on every orientation event, instead sync to requestAnimationFrame

When to use device orientation events

There are several uses for device orientation events. For example:

  • Update a map as the user moves.
  • Subtle UI tweaks, for example adding paralax effects.
  • Combined with GeoLocation, can be used for turn by turn navigation.

Check for support and listen for events

To listen for DeviceOrientationEvent, first, check to see if the events are supported in the browser. Then, attach an event listener to the window object listening for deviceorientation events.

    if (window.DeviceOrientationEvent) {
      window.addEventListener('deviceorientation', deviceOrientationHandler, false);
      document.getElementById("doeSupported").innerText = "";
    }
    
View full sample

Handle the device orientation events

The device orientation event fires when the device moves, or changes orientation. It returns data about the difference between the device in it’s current position in relation to the Earth coordinate frame.

The event typically returns three properties, alpha, beta, and gamma. On Mobile Safari, and additional parameter webkitCompassHeading is returned with the compass heading.

Updated on 2014-06-17

Authors

Pete LePage

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the Apache 2.0 License. For details, see our Site Policies.