Screen Orientation Detection in JavaScript
Detect and respond to device orientation changes using the Screen Orientation API, the orientation media query, and legacy orientationchange events.
Detailed Explanation
Screen Orientation API
The Screen Orientation API provides a modern, standardized way to detect the device's current orientation and listen for changes.
Reading Current Orientation
const orientation = screen.orientation;
console.log(orientation.type); // "landscape-primary"
console.log(orientation.angle); // 0
Orientation Types
| Type | Angle | Description |
|---|---|---|
| portrait-primary | 0 | Normal portrait (phone upright) |
| portrait-secondary | 180 | Upside-down portrait |
| landscape-primary | 90 | Landscape, rotated clockwise |
| landscape-secondary | 270 | Landscape, rotated counter-clockwise |
Listening for Changes
screen.orientation.addEventListener('change', () => {
console.log('New orientation:', screen.orientation.type);
console.log('New angle:', screen.orientation.angle);
});
CSS Orientation Media Query
@media (orientation: portrait) {
.sidebar { display: none; }
}
@media (orientation: landscape) {
.sidebar { display: block; width: 250px; }
}
Note: The CSS orientation query is based on the viewport aspect ratio (height > width = portrait), not the physical device orientation.
Locking Orientation (Fullscreen Only)
// Request fullscreen first
document.documentElement.requestFullscreen().then(() => {
screen.orientation.lock('landscape-primary');
});
// Unlock
screen.orientation.unlock();
Legacy Approach
The older orientationchange event still works but is deprecated:
// Deprecated but widely supported
window.addEventListener('orientationchange', () => {
console.log('Orientation angle:', window.orientation);
});
Desktop Considerations
On desktop browsers, orientation is typically landscape-primary with angle 0. The orientation type changes when:
- A laptop/tablet is physically rotated
- The user changes display settings in the OS
- The viewport aspect ratio changes (for CSS media queries)
Use Case
Developers building full-screen games, video players, or mobile-optimized apps need to detect orientation changes to adjust layouts, lock orientation during gameplay, or show rotation prompts.
Try It — Screen Info Display
Related Topics
Viewport Size vs Screen Resolution: Key Differences
Viewport & Screen
Screen Available Area (availWidth, availHeight)
Viewport & Screen
How to Detect Touch Devices in JavaScript
Touch & Input
window.innerWidth vs window.outerWidth Explained
Viewport & Screen
Tailwind CSS Responsive Breakpoints Reference
Responsive Breakpoints