Device orientation on the browser

From Publication Station
Jump to navigation Jump to search

To detect the orientation of devices where the web browser is running, using Javascript, we rely on the window.addEventListener("deviceorientation") that listens to the orientation of the device.


See it running in:


<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src=""></script> 

    <script defer src=""></script>
      body {
        margin: 2em;
    <title>Device orientation</title>
    <style type="text/css">
      .h5logo {
        width: 50%;
        display: block;
        margin-left: auto;
        margin-right: auto;

    <div role="main" class="container">
      <h1>Device Orientation</h1>
      <p>example from <a href=""></a></p>
        Device orientation is <b><span id="doeSupported">not</span></b> supported 
        on your device.

      <img id="h5logo" src="" class="h5logo">

      <h2>Rotation Data</h2>
        <b>alpha:</b> <span id="alpha"></span><br>
        <b>beta:</b> <span id="beta"></span><br>
        <b>gamma:</b> <span id="gamma"></span><br>

        <b>Last updated:</b> <span id="timestamp"></span>

    <script type="text/javascript">

      var fixed = 2;
      var h5logo  = $("#h5logo");
      var timestamp = $("#timestamp");
      var alpha = $("#alpha");
      var beta = $("#beta");
      var gamma = $("#gamma");

      /* // [START devori] */
      if (window.DeviceOrientationEvent) {
        window.addEventListener('deviceorientation', deviceOrientationHandler, false);
        $("#doeSupported").innerText = "";
      /* // [END devori] */

      var deviceOrientationData;

      function deviceOrientationHandler(evt) {
        deviceOrientationData = evt;
        try {
            timestamp.text( new Date(evt.timeStamp));
            alpha.text( evt.alpha.toFixed(fixed) );
            beta.text(  evt.beta.toFixed(fixed) );
            gamma.text( evt.gamma.toFixed(fixed) );
          var rotation = "rotate("+ evt.alpha +"deg) rotate3d(1,0,0, "+ (evt.gamma * -1)+"deg)";
	    h5logo.css('transform', rotation).css('webkitTransform', rotation);
        } catch (ex) {


Emulate device orientation

On a desktop computer the device orientation can be emulated by the browser.

In Chrome sensors can be simulated by:

  • Opening the DevTools main menu, then
  • Under More Tools, clicking on Sensors


More info at:

more on Device orientation/motion

debugging mobile browsers

debugging Firefox over Wifi