How to detect device orientation with JavaScript?
<p>I've seen a number of ways to detect the screen orientation of the device, including using a check to test innerWidth versus innerHeight, like so.</p>

<pre><code>function getOrientation(){
    var orientation = window.innerWidth &gt; window.innerHeight ? "Landscape" : "Primary";
    return orientation;
}
</code></pre>

<p>But what if I want to check for <em>changes</em> in screen orientation as well with an event listener? I've tried this code but it doesn't work for me.</p>

<pre><code>  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();
</code></pre>

<p>It doesn't detect device orientation, and the listener does not register for me (I'm using Chrome's device emulator).</p>