How to detect screen orientation change with JavaScript

This is the easiest way to detect if your smartphone (Android, iPhone, …) or tablet device (iPad, Galaxy Tab, …) is in portrait mode or landscape mode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function doOnOrientationChange()
{
  switch(window.orientation) 
  {  
    case -90:
    case 90:
      alert('landscape');
      break; 
    default:
      alert('portrait');
      break; 
  }
}
 
window.onorientationchange = function()
{
  doOnOrientationChange();
};
 
// Initial execution
doOnOrientationChange();

The code also detects if the screen orientation has changed.