How to use the Device Orientation API

Today we have mobile devices that come equipped with everything from cameras to geolocation, and we have little computers in our hands that can do pretty much anything we do with our desktop.

One of the key APIs that functions with mobile devices is the Device Orientation API.

The Device Orientation API helps us as developers detect the orientation of the user’s screen and make the necessary changes to our layout.

For example, on YouTube, if you are watching a video and you tilt your phone, the video goes fullscreen, that uses this API.

Browser support

The browser support for this API is pretty good for a new API, it’s supported by all major browsers except Safari and IE supports it with version 11.

Using this API

When it comes to these types of feature the first thing we always need to do is to test for support in the user’s browser:

if (window.DeviceOrientationEvent) {
 // Supported you can continue
}

This is all it takes to test for support.

After this we’ll first we need to listen for orientation changes with the deviceorientation event:

window.addEventListener("deviceorientation", orientation, true);

Via this listener we can retrieve four different values from the API:

  • absolute – this value indicates whether or not the device is providing the value absolutely.
  • alpha – the alpha value will be a value from 0 to 360 that will represent the motion of the device on the z axis.
  • beta – the beta value represents the motion in the x axis and the values range from -180 to 180.
  • gamma – the last value represents the motion in the y axis and it has values from -90 to 90.

You don’t have to use all of these values, just the ones that you need. For example if I want a div to move with the device’s orientation I’ll only use beta and gamma, like so:

function orientation(event) {
  var x = event.beta;
  var y = event.gamma;
}

We can now use the x and y variables to control the movement of a div and to do that all we need to do is use jQuery’s css method and set the top the x and the left to the y:

function orientation(event) {
  var x = event.beta;
  var y = event.gamma;

  $('.square').css({
    'top':x,
    'left': y
  });
}

To see a demo, check out this pen I created.

Conclusion

This type of API is very often overlooked because it’s so simple, but it can deliver a huge boost to your UX.

The option to accommodate however your user likes to hold his or her device, is the kind of attention to detail that keeps users coming back time and again.

Sara Vieira is a freelance Web Designer and Developer with a passion for HTML5/CSS3 and jQuery. You can follow her on twitter or check out her website. More articles by Sara Vieira
Home CSS Deals HTML HTML5 Java JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress