Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions javascript javascript

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions


if(window.innerHeight > window.innerWidth){    alert("Please use Landscape!");}

jQuery Mobile has an event that handles the change of this property... if you want to warn if someone rotates later - orientationchange

Also, after some googling, check out window.orientation (which is I believe measured in degrees...)

EDIT: On mobile devices, if you open a keyboard then the above may fail, so can use screen.availHeight and screen.availWidth, which gives proper height and width even after the keyboard is opened.

if(screen.availHeight > screen.availWidth){    alert("Please use Landscape!");}


You can also use window.matchMedia, which I use and prefer as it closely resembles CSS syntax:

if (window.matchMedia("(orientation: portrait)").matches) {   // you're in PORTRAIT mode}if (window.matchMedia("(orientation: landscape)").matches) {   // you're in LANDSCAPE mode}

Tested on iPad 2.


David Walsh has a better and to the point approach.

// Listen for orientation changeswindow.addEventListener("orientationchange", function() {  // Announce the new orientation number  alert(window.orientation);}, false);

During these changes, the window.orientation property may change. A value of 0 means portrait view, -90 means a the device is landscape rotated to the right, and 90 means the device is landscape rotated to the left.

http://davidwalsh.name/orientation-change