2 min read

Device Orientation and Motion API

The Device Orientation and Motion API provides access to the gyroscope, accelerometer, and compass data of a mobile device. This allows web applications to determine the physical orientation and movement of the device.

1. Device Orientation

The deviceorientation event provides information about the physical orientation of the device in space. It returns rotation data around three axes.

The Axes

  • Alpha (Z-axis): Rotation around the z-axis (0 to 360 degrees). Think of a compass; 0 is North.
  • Beta (X-axis): Rotation around the x-axis (-180 to 180 degrees). Front-to-back tilt.
  • Gamma (Y-axis): Rotation around the y-axis (-90 to 90 degrees). Left-to-right tilt.

Basic Usage

window.addEventListener("deviceorientation", (event) => {
  const alpha = event.alpha;
  const beta = event.beta;
  const gamma = event.gamma;

  console.log(`Alpha: ${alpha}, Beta: ${beta}, Gamma: ${gamma}`);

  // Example: Rotate an element based on device tilt
  const box = document.querySelector('.box');
  box.style.transform = `rotate(${alpha}deg) rotateX(${beta}deg) rotateY(${gamma}deg)`;
});

2. Device Motion

The devicemotion event provides information about the acceleration of the device.

Properties

  • acceleration: Acceleration along the X, Y, and Z axes (excluding gravity).
  • accelerationIncludingGravity: Acceleration along the X, Y, and Z axes (including gravity). If the phone is resting flat on a table, Z will be ~9.8 m/s².
  • rotationRate: The rate of rotation (degrees per second) around the Z (alpha), X (beta), and Y (gamma) axes.
  • interval: The interval (in milliseconds) at which data is obtained.

Basic Usage

window.addEventListener("devicemotion", (event) => {
  const acc = event.acceleration;
  const accG = event.accelerationIncludingGravity;
  const rot = event.rotationRate;

  console.log(`Acceleration X: ${acc.x}, Y: ${acc.y}, Z: ${acc.z}`);
  console.log(`Rotation Rate Alpha: ${rot.alpha}, Beta: ${rot.beta}, Gamma: ${rot.gamma}`);
});

3. Permissions (iOS 13+)

For privacy reasons, modern versions of iOS (and potentially other browsers) require explicit user permission to access these sensors. You must request permission in response to a user gesture (like a click).

const btn = document.getElementById("request-btn");

btn.addEventListener("click", () => {
  if (typeof DeviceMotionEvent.requestPermission === 'function') {
    DeviceMotionEvent.requestPermission()
      .then(permissionState => {
        if (permissionState === 'granted') {
          window.addEventListener('devicemotion', (e) => {
            // ... handle motion ...
          });
        }
      })
      .catch(console.error);
  } else {
    // Non-iOS 13+ devices
    window.addEventListener('devicemotion', (e) => {
       // ... handle motion ...
    });
  }
});

4. Use Cases

  • Gaming: Controlling a character by tilting the phone.
  • VR/AR: Looking around a 360-degree scene.
  • Compass: Determining direction.
  • Gestures: Shake to undo.

programming/javascript/vanilla/javascript programming/javascript/vanilla/events programming/javascript/vanilla/geolocation-api