jvilhena
jvilhena

Reputation: 1131

Detect if browser/device supports screen rotation

Is there a way to detect if the browser/device supports screen rotation, without having to wait for the orientationchange event? I'm not trying to detect the rotation itself, only if the browser or device supports it.

Upvotes: 5

Views: 1867

Answers (2)

Zach Saucier
Zach Saucier

Reputation: 25954

You should assume that all devices can change their orientation because you can turn any screen to the other orientation using the OS. This is unless you lock the orientation, which is not recommended in most cases.

Technically, window.orientation and window.orientationchange are deprecated. We should instead use the screen.orientation object and change event listener.

However, Safari does not yet support screen orientation. So you should have both for now:

if (screen.orientation) {
  screen.orientation.addEventListener('change', handleOrientationChange);
} else {
  window.addEventListener('orientationchange', handleOrientationChange);
}

When the device is not rotated this listener will not fire. But it could fire for any device.

For more information, see "Managing screen orientation" in MDN's docs.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

I think you can detect it like so:

if( 'onorientationchange' in window) { /* supported! */ }

However, I'm not sure if some browsers will support the event even though they never fire it.

Upvotes: 5

Related Questions