DEV Community

MD ASHRAF
MD ASHRAF

Posted on

Handling Device orientation in Javascript

The window.orientation property returns a numeric value indicating the device's orientation:

- 0 or 180: Portrait mode

portrait mode

- 90 or -90: Landscape mode

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');
}
Enter fullscreen mode Exit fullscreen mode

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).

Image portrait primary

  • portrait-secondary: The device is in portrait mode, but the screen is oriented upside-down (e.g., the home button is at the top).

Image portrait secondary

  • 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).

Image landscape primary

  • 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).

Image landscape secondary

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)