Tag Archives: orientation

Detect iPhone / iTouch Orientation – Change In Your Code

I have been working on a template for an iPhone Library Application today, its pretty simple stuff, A search, Asynchonous paginated results with the full details on each result. It will be using FileMaker for its database, but currently I am searching a large PHP array for testing.

When displaying the full result, when your phone is help upright, the results look good, but when you roll the phone over, the display is crap so after a fair amount of googling and multiple sources linking to Apple, and a missing page http://developer.apple.com/samplecode/iPhoneOrientation/index.html I found this post @ DevPhone.com.

Its exactly what I wanted. If you need an iPhone/iPod touch Application or web application, contact me via iPhone Web Application @ www.webapp.co.nz.

window.onorientationchange = function() {
  /*window.orientation returns a value that indicates whether iPhone is in portrait mode, landscape mode with the screen turned to the
    left, or landscape mode with the screen turned to the right. */
  var orientation = window.orientation;
  switch(orientation) {

    case 0:
        /* If in portrait mode, sets the body's class attribute to portrait. Consequently, all style definitions matching the body[class="portrait"] declaration
           in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
        document.body.setAttribute("class","portrait");

        /* Add a descriptive message on "Handling iPhone or iPod touch Orientation Events"  */
        document.getElementById("currentOrientation").innerHTML="Now in portrait orientation (Home button on the bottom).";
        break;

    case 90:
        /* If in landscape mode with the screen turned to the left, sets the body's class attribute to landscapeLeft. In this case, all style definitions matching the
           body[class="landscapeLeft"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
        document.body.setAttribute("class","landscapeLeft");

        document.getElementById("currentOrientation").innerHTML="Now in landscape orientation and turned to the left (Home button to the right).";
        break;

    case -90:
        /* If in landscape mode with the screen turned to the right, sets the body's class attribute to landscapeRight. Here, all style definitions matching the
           body[class="landscapeRight"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */
        document.body.setAttribute("class","landscapeRight");

        document.getElementById("currentOrientation").innerHTML="Now in landscape orientation and turned to the right (Home button to the left).";
        break;
  }
}