The window.orientation property returns a numeric value indicating the device's orientation:
- 0 or 180: Portrait mode
- 90 or -90: Landscape mode
// Check if the screen orientation API is supported
if (window.screen.orientation) {
// Add an event listener for the change event
window.screen.orientation.addEventListener('change', function () {
// Log the current orientation type
console.log('Orientation changed to:', window.screen.orientation.type);
});
// Log the initial orientation type
console.log('Initial orientation:', window.screen.orientation.type);
} else {
console.log('Screen orientation API not supported');
}
When you run this code, it will log the initial orientation type and then log the new orientation type whenever the device's screen orientation changes.
Output
The possible values for window.screen.orientation.type are:
- portrait-primary: The device is in portrait mode, with the screen oriented in the standard way (e.g., the home button is at the bottom).
- portrait-secondary: The device is in portrait mode, but the screen is oriented upside-down (e.g., the home button is at the top).
- landscape-primary: The device is in landscape mode, with the screen oriented in the standard way (e.g., the home button is on the right side).
- landscape-secondary: The device is in landscape mode, but the screen is oriented in the opposite way (e.g., the home button is on the left side).
Here's an example output:
Initial orientation: portrait-primary
Orientation changed to: landscape-primary
Orientation changed to: portrait-primary
Orientation changed to: landscape-secondary
This output shows the initial orientation and the changes that occur when the device is rotated.
Top comments (0)