39ro
39ro

Reputation: 902

Detect screen orientation with JavaScript

I need to detect the change between the orientation of a device at runtime: trying to use the Screen Api (https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation) on an Angular project I am receiving an error: Property 'orientation' does not exist on type 'Screen'.
Orientation is not present in the Screen interface!

That some solutions that I was trying to replicate, without having success:
- How do I correctly detect orientation change using javascript and Phonegap in IOS?

How could I achieve it in a cross-browser friendly way?

Scenario:

count = 0;
countState() {
  (window.screen.orientation.type === 'landscape-primary' || window.screen.orientation.type === 'landscape-secondary') ? count++ : count--;
}
<button (click)="countState()">Count</button>

Upvotes: 0

Views: 7063

Answers (2)

Emin Temiz
Emin Temiz

Reputation: 111

The orientation read-only property of the Screen interface returns the current orientation of the screen.

Syntax

var orientation = window.screen.orientation;

Example

var orientation = (screen.orientation || {}).type || screen.mozOrientation || screen.msOrientation;

if (orientation === "landscape-primary") {
  console.log("That looks good.");
} else if (orientation === "landscape-secondary") {
  console.log("Mmmh... the screen is upside down!");
} else if (orientation === "portrait-secondary" || orientation === "portrait-primary") {
  console.log("Mmmh... you should rotate your device to landscape");
} else if (orientation === undefined) {
  console.log("The orientation API isn't supported in this browser :(");
}

Upvotes: 3

Ben Kolya Mansley
Ben Kolya Mansley

Reputation: 1793

I suppose a possible, simple solution would be something like this:

function getOrientation() {
  if (window.outerWidth > window.outerHeight) {
    return 'landscape';
  return 'portrait';
}

Upvotes: 0

Related Questions