Device Orientation

The Device Orientation API allows Web applications to access the gyroscope and compass data in order to determine the orientation of the user's device in all the three dimensions, expressed in degrees of divergence from the "natural" northbound lie flat position.

For the detection of the device's movements, see Device Motions.

API glimpse

window.addEventListener('deviceorientation', listener)
An event fired when the significant changes in the device's orientation has occured.
event.alpha
Returns device's current heading (direction) in degrees, counted counterclockwise from the North (0) through West (90), South (180) and East (270).
event.beta
Returns device's current front/back tilt in degrees, 0 when lying horizontally upward facing, 90 when in vertical position, -90 in vertical upside down, -180 when horizontal upside down.
event.gamma
Returns device's current left/right tilt in degrees, from -90 when turned left to 90 when turned right.

Live Demo

Tilt Left/Right [gamma]
Tilt Front/Back [beta]
Direction [alpha]

Demo from HTML5 Rocks article.

  • if ('DeviceOrientationEvent' in window) {
      window.addEventListener('deviceorientation', deviceOrientationHandler, false);
    } else {
      document.getElementById('logoContainer').innerText = 'Device Orientation API not supported.';
    }
    
    function deviceOrientationHandler (eventData) {
      var tiltLR = eventData.gamma;
      var tiltFB = eventData.beta;
      var dir = eventData.alpha;
      
      document.getElementById("doTiltLR").innerHTML = Math.round(tiltLR);
      document.getElementById("doTiltFB").innerHTML = Math.round(tiltFB);
      document.getElementById("doDirection").innerHTML = Math.round(dir);
    
      var logo = document.getElementById("imgLogo");
      logo.style.webkitTransform = "rotate(" + tiltLR + "deg) rotate3d(1,0,0, " + (tiltFB * -1) + "deg)";
      logo.style.MozTransform = "rotate(" + tiltLR + "deg)";
      logo.style.transform = "rotate(" + tiltLR + "deg) rotate3d(1,0,0, " + (tiltFB * -1) + "deg)";
    }
  • <table class="table table-striped table-bordered">
      <tr>
        <td>Tilt Left/Right [gamma]</td>
        <td id="doTiltLR"></td>
      </tr>
      <tr>
        <td>Tilt Front/Back [beta]</td>
        <td id="doTiltFB"></td>
      </tr>
      <tr>
        <td>Direction [alpha]</td>
        <td id="doDirection"></td>
      </tr>
    </table>
    
    <div class="container" id="logoContainer">
      <img src="https://www.w3.org/html/logo/downloads/HTML5_Badge_512.png" id="imgLogo">
    </div>
    
    <p><small>Demo from <a href="https://www.html5rocks.com/en/tutorials/device/orientation/" target="_blank">HTML5 Rocks</a> article.</small></p>
  • .container {
      perspective: 300;
      -webkit-perspective: 300;
    }
    
    #imgLogo {
      width: 275px;
      margin-left: auto;
      margin-right: auto;
      display: block;
      padding: 15px;
    }

Resources