How to determine device orientation using JavaScript?

I saw several ways to determine the screen orientation of a device, including using a check to check innerWidth and innerHeight, for example.

function getOrientation(){ var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Primary"; return orientation; } 

But what if I want to check for changes in screen orientation, as well as with an event listener? I tried this code, but it does not work for me.

  function doOnOrientationChange() { switch(window.orientation) { case -90: case 90: alert('landscape'); break; default: alert('portrait'); break; } } window.addEventListener('orientationchange', doOnOrientationChange); // Initial execution if needed doOnOrientationChange(); 

It does not determine the orientation of the device, and the listener does not register for me (I use the Chrome device emulator).

+5
source share
1 answer

Two ways to do this:

Firstly, according to the Screen API documentation, using> = Chrome 38, Firefox, and IE 11, the display object is available not only to view the orientation, but also to register a listener each time the device orientation changes.

screen.orientation.type will explicitly tell you what orientation is, and for the listener you can use something simple:

 screen.orientation.onchange = function (){ // logs 'portrait' or 'landscape' console.log(screen.orientation.type.match(/\w+/)[0]); }; 

Secondly, for compatibility with other browsers, such as Safari, which are not compatible with Screen, this post shows that you can continue to use innerWidth and innerHeight when resizing the window.

  function getOrientation(){ var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Portrait"; return orientation; } window.onresize = function(){ getOrientation(); } 
+12
source

Source: https://habr.com/ru/post/1247222/


All Articles