iPhone Orientation

Summary

Experiments with the special onorientationchange event. Also works with window.orientation property.

Example

This only works on the iPhone. If the orientation is "portrait," the screen is green, and the text below says "Orientation is at ZERO." If "landscape," the screen is pink, and the text below says "Orientation is at NINETY" or "NEGATIVE NINETY."

You are reading this because you're on a regular computer and not an iPhone.

Date Created

22 Nov 2008.

Help

  1. Web Development for the iPhone :: CSS, JavaScript and XHTML Explained from the iPhone Basic experiment introduced an option to do something with the iPhone's orientation. Led to search online.
  2. Ajaxian » iPhone window.onorientationchange Code shows how simple it is to use window.orientation and onorientationchange to change content/layout based on the iPhone's orientation.

Process

Trial and Error. Had to wait until I see my sister to borrow her iPhone to test the page. I was excited when I saw it work.

  1. Test page.

The Code

Here’s the code. Please link back here if you’re using it.

Put this CSS in the head tag.

.portrait{
padding:10px;
background-color:#00FF00;
}
            
.landscape{
padding:30px;
background-color:#FF3366;
}

Put this HTML in the head tag.

<div id='text' >
    You are reading this because you're on a regular computer and not an iPhone.
</div>

Put this JavaScript in the body tag, after the object was created.

var text=document.getElementById("text");

function applyOrientationScript(){
    var winOr=window.orientation;
    
    switch (winOr){
        case 0:
            text.innerHTML="Orientation is at ZERO";
            document.body.setAttribute("class","portrait");
            break;
        
        case 90:
            text.innerHTML="Orientation is at NINETY";
            document.body.setAttribute("class","landscape");
            break;
            
        case -90:
            text.innerHTML="Orientation is at NEGATIVE NINETY";
            document.body.setAttribute("class","landscape");
            break;
        }
    }


window.onorientationchange=applyOrientationScript;

applyOrientationScript();

Return to top