Javascript Mobile Orientation Detection

Today I wanted to share with you how to detect the orientation of a mobile device such as iPhone, iPad, Blackberry even the Android with JavaScript alone. Before we start we should talk about “Media Queries” for CSS3.

CSS3 media queries allow you to change the layouts/look and feel of your site by means of screen side detection. The problem however with CSS3 media queries you can’t manipulate the DOM markup of a document based on these screen sizes that are detected.

With the help of JavaScript however, we can now manipulate DOM markup by determining the orientation of a mobile device. With the window.onorientationchange feature of most grade A mobile devices we can both listen for orientation change or detect orientation upon page loadings.

Here is our script:

window.onorientationchange = detectOrientation;
function detectOrientation(){
	if(typeof window.onorientationchange != 'undefined'){
		if ( orientation == 0 ) {
	 		//Do Something In Portrait Mode
		else if ( orientation == 90 ) {
	 		//Do Something In Landscape Mode
		else if ( orientation == -90 ) {
	 		//Do Something In Landscape Mode
		else if ( orientation == 180 ) {
	 		//Do Something In Landscape Mode

With the above JavaScript, upon the page loading we determine right away what the orientation of our device is by calling the function “detectOrientation();”. From here we have a condition that checks the “typeof” our “window.onorientationchange” to see if truly the feature exists for the device or not. If indeed the ability of “window.onorientationchange” is there for a device we travel further down into more conditions based on the devices orientation direction (0,90,-90,180).

In each orientation detection we cause begin to manipulate our document however we wish! Very nifty!

Down side is there is only one portrait detection, leaving some devices such as iPad unable to detect it being in portrait mode with the device held upside down.

So to conclude, with the power of most new mobile devices utilizing CSS3 media queries and now “window.onorientationchange” we have the power to manipulate almost all of our document however we like to best fit our visitors devices.

Thanks to the original creator of the above script:

Devin R. Olsen

Located in Portland Oregon. I like to teach, share and dabble deep into the digital dark arts of web and game development.

More Posts

Follow Me:
TwitterFacebookGoogle Plus