O'Reilly logo

HTML5 and JavaScript Web Apps by Wesley Hales

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 8. Device Orientation API

Accelerometers, gyroscopes, and compasses are now commonplace in mobile devices and laptops. With the Device Orientation API, you can capture movements at an extremely fine-grained level, receiving exact details on the motion and acceleration of the device.

Conceptually, an accelerometer behaves as a damped mass on a spring. When the accelerometer experiences an acceleration, the mass is displaced to the point that the spring is able to accelerate the mass at the same rate as the casing. The displacement is then measured to give the acceleration.

With applications ranging from military-based inertial guidance systems to tracking animals to measuring earthquakes and aftershocks, orientation hardware has been in use for quite some time. Now you have the opportunity to add this functionality to your applications to enhance how devices are tracked and interact with your user interface. It’s time to move beyond using the Device Orientation API only for games and simple Geolocation.

To begin, you need to understand the basics of the API and handling the measurements in JavaScript. The first DOM event provided by the specification, deviceorientation, supplies the physical orientation of the device, expressed as a series of rotations from a local coordinate frame. Here’s a simple check to see if this browser supports the DeviceOrientationEvent object:

supports_orientation : function() {
  try {
  return 'DeviceOrientationEvent' in
  window && window['DeviceOrientationEvent' ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required