トップへ(mam-mam.net/)

Get the Screen Orientation of a Smartphone on a Website

Japanese

Getting the Screen Orientation of a Smartphone with JavaScript

To get the screen orientation, use screen.orientation.type, which returns one of the following values:

portrait-primary
Portrait (top side up)
portrait-secondary
Portrait (top side down)
landscape-primary
Landscape (top side on the left)
landscape-secondary
Landscape (top side on the right)
You can check the current rotation angle with screen.orientation.angle.
When the screen orientation changes, the screen.orientation.onchange event is triggered.

Example

Try rotating your device to see the screen orientation change.


Source Code

<div id="ori"></div>

<script>
  window.addEventListener("load",function(){
    getOrientation();
    screen.orientation.onchange=function(){
      getOrientation();;
    }
  });
  function getOrientation(){
    let type = screen.orientation.type;
    let ori = "";
    if(type == "portrait-primary"){
      ori = "Portrait (top side up)";
    }else if(type == "portrait-secondary"){
      ori = "Portrait (top side down)";
    }else if(type == "landscape-primary"){
      ori = "Landscape (top side on the left)";
    }else if(type == "landscape-secondary"){
      ori = "Landscape (top side on the right)";
    }
    document.getElementById("ori").innerHTML=
      ori+" "+screen.orientation.angle+"degrees<br>"+
          "<img src='./imgs/"+type+".png'>";
  }
</script>