Detect Landscape/Portrait Mode using JavaScript

Detecting device mode (landscape or portrait) using CSS3 is now very much easy and it is state of art. But it wont work on certain situations like I had. I failed to make @media queries detect device oriantaion on Iphone. So I came to write a JavaScript fix to get work done.

Check my oriantation test using CSS3 @media queries here. The demo page should show text ‘Portrait’ on portrait mode and ‘Landscape’ on respective mode. But it does not. You might want to try with you own device. Some of my friends said it is working. Check out the discussions on Forrst.

I Googled for the solutions, but I must say I couldn’t find any reliable one :(. If you prefer to use CSS3 media queries, check out the post on Stuff & Nonsense. And here it goes my JavaScript function that will detect the landscape/portrait mode.

First, lets create a function called ‘checkOrientation‘ so that we can evoke it by just a name instead of repeating whole lines.

Inside this function we will check the device oriantion degree which we are going to take from window.oriantation method. If we get the degree 0 its the mode portrait else its landscape.  Since we will be using window. orientation method, this function will only work in handheld devices. So here it goes our function:

function checkOrientation(){
      var currMode = "";

      switch(window.orientation){

           case 0:
           currMode = "portrait";
           break;

           case -90:
           currMode = "landscape";
           break;

           case 90:
           currMode = "landscape";
           break;

           case 180:
           currMode = "landscape";
           break;
     }
     document.getElementsByTagName("body")[0].setAttribute("class", currMode);
}

I have used switch statement to set the currMode variable, which we are going to use as class on required html elements. I set that class on body.

Now its time to call the function, you can call it directly or on window.load method. I think window.load method is better and safe. So lets call it:

window.load = function() {
     checkOrientation();
}

When our page is ready, check the class of body element. We are done. But wait what if we change the oriantaion now? Yes, we need to update the class on oriantation change.

For this, we have window.onorientationchange method, which is also available on devices only. We will recall our function inside this method:

window.onorientationchange = function(){
      checkOrientation();
}

Thats it. Now we are completely done. Check-out the Landscape/Portrait Mode detection demo.

Comments

comments

Powered by Facebook Comments

One thought on “Detect Landscape/Portrait Mode using JavaScript”

Comments are closed.