codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🎨

HTML & CSS

40 / 59 topics
34HTML5 History API35HTML5 Web Workers36HTML5 Service Workers37HTML5 Fetch API38HTML5 WebSockets39HTML5 Geolocation API40HTML5 Device Orientation API41HTML5 Payment Request API42HTML5 Push Notifications
Tutorials/HTML & CSS/HTML5 Device Orientation API
🎨HTML & CSS

HTML5 Device Orientation API

Updated 2026-04-20
3 min read

HTML5 Device Orientation API

Introduction

The HTML5 Device Orientation API allows web applications to access information about the orientation and movement of a device. This can be particularly useful for creating immersive experiences, such as augmented reality (AR) or interactive games that respond to user movements.

In this tutorial, we will explore how to use the Device Orientation API to detect changes in device orientation and implement real-world examples. We'll cover the basics of accessing the API, handling events, and best practices for using it effectively.

Prerequisites

Before diving into the implementation, ensure you have a basic understanding of HTML, CSS, and JavaScript. Familiarity with event-driven programming is also beneficial.

Understanding Device Orientation Data

The Device Orientation API provides three main pieces of information:

  1. Alpha: Represents the rotation around the Z-axis (yaw), measured in degrees from 0 to 360.
  2. Beta: Represents the rotation around the X-axis (pitch), measured in degrees from -180 to 180.
  3. Gamma: Represents the rotation around the Y-axis (roll), measured in degrees from -90 to 90.

Additionally, the API provides acceleration and rotation rate data, which can be useful for more advanced applications.

Accessing Device Orientation Data

To access device orientation data, you need to request permission from the user. This is done using the DeviceOrientationEvent.requestPermission() method. Once permission is granted, you can listen for the deviceorientation event to receive updates on device orientation changes.

Example: Requesting Permission and Listening for Events

// Check if Device Orientation API is supported
if (window.DeviceOrientationEvent) {
  // Request permission from the user
  DeviceOrientationEvent.requestPermission()
    .then(permissionState => {
      if (permissionState === 'granted') {
        // Listen for device orientation events
        window.addEventListener('deviceorientation', handleDeviceOrientation);
      } else {
        console.log('Permission denied');
      }
    })
    .catch(console.error);
} else {
  console.log('Device Orientation API not supported');
}

// Event handler for device orientation changes
function handleDeviceOrientation(event) {
  const alpha = event.alpha;
  const beta = event.beta;
  const gamma = event.gamma;

  // Use the orientation data as needed
  console.log(`Alpha: ${alpha}, Beta: ${beta}, Gamma: ${gamma}`);
}

Explanation

  1. Check API Support: Before attempting to use the API, check if DeviceOrientationEvent is supported in the user's browser.
  2. Request Permission: Use requestPermission() to ask the user for permission to access device orientation data.
  3. Listen for Events: Add an event listener for deviceorientation to receive updates whenever the device's orientation changes.
  4. Handle Events: Implement a function to process the orientation data, such as logging it or using it to update the UI.

Best Practices

  1. User Experience: Always request permission in response to user interaction (e.g., button click) rather than automatically on page load.
  2. Error Handling: Handle cases where permission is denied or the API is not supported gracefully.
  3. Performance Considerations: Be mindful of performance, especially when updating the UI frequently based on orientation changes.

Real-World Example: Interactive Compass

Let's create a simple interactive compass that rotates to match the device's orientation.

HTML Structure

<div id="compass">
  <div id="needle"></div>
</div>

CSS Styling

#compass {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  border: 2px solid #333;
  position: relative;
}

#needle {
  width: 4px;
  height: 100px;
  background-color: red;
  position: absolute;
  top: 50%;
  left: 50%;
  transform-origin: bottom center;
}

JavaScript Implementation

function handleDeviceOrientation(event) {
  const alpha = event.alpha;

  // Rotate the needle based on alpha value
  document.getElementById('needle').style.transform = `rotate(${alpha}deg)`;
}

// Request permission and listen for device orientation events
if (window.DeviceOrientationEvent) {
  DeviceOrientationEvent.requestPermission()
    .then(permissionState => {
      if (permissionState === 'granted') {
        window.addEventListener('deviceorientation', handleDeviceOrientation);
      } else {
        console.log('Permission denied');
      }
    })
    .catch(console.error);
} else {
  console.log('Device Orientation API not supported');
}

Explanation

  1. HTML: A simple structure with a div for the compass and another for the needle.
  2. CSS: Basic styling to create a circular compass with a red needle.
  3. JavaScript: Rotate the needle based on the alpha value from the device orientation event.

Conclusion

The HTML5 Device Orientation API provides powerful capabilities for creating interactive web applications that respond to user movements. By understanding how to access and use this data, you can build engaging experiences that leverage the full potential of modern devices.

Remember to always prioritize user experience and handle edge cases gracefully to ensure your application works well across different browsers and devices.


PreviousHTML5 Geolocation APINext HTML5 Payment Request API

Recommended Gear

HTML5 Geolocation APIHTML5 Payment Request API