Today is a good day to code

iPhone onorientationchange Event

Posted: December 31st, 1969 | Author: | Filed under: iPhone, java, Programming, Uncategorized | Tags: , | 1 Comment »

iPhone onorientationchange Event

Picture of Irvin* Update: I was wrong about this, it won't work. you have to use the dirty markup method and put it in the body tag. Safari's DOM renderer processes the JavaScript in parallel, so the body element is not recognized by the JavaScript if it is at the top. There are other ways to delay the execution of this command until the DOM is rendered, but they aren't worth the trouble *

I'm glad that Apple has created this event. I think most of the developers who started early with the iUI were polling for the window.innerWidth. While this was an awesome hack before Apple had a proper event. Well now they do, but I don't really like their example code.

It is somewhat nitpicky, but applying an event handler to an element explicitly in the DOM is not the best way to do it, besides not being valid HTML / XHTML, it is sloppy. Some would argue that most validator plugins will detect your addition of the event handler post rendering anyway, but at least your html looks clean for debugging if you don't have strings of event handlers on all of your elements!

At any rate, what Apple's example shows is:

That will work as long as your JavaScript libraries are included before the body element, something that YSlow! and Yahoo! suggest hurt performance. I don't agree with Yahoo! on their performance guidelines most of the time, but in this case, I have seen the improvement, and I am now a believer.

If you leave your markup alone and add the event handler in one of your JavaScript files like:

document.getElementsByTagName(“body”)[0].onorientationchange = updateOrientation;

Then your markup will remain clean, you can move your JavaScript script include tags to just before your closing body tag, and you will have a quick and efficient page.

If you are handling the orientation event, it will return 0 for portrait, -90 for landscape after a clockwise turn or to the right, and 90 for landscape after a counter-clockwise turn, or to the left if the screen is facing you.

For most cases, you would have to determine if it was not 0, like this:

if(window.orientation != 0){
// iPhone is in landscape mode
}else{
// iPhone is in portrait mode
}

That is simplistic, but it should get you started. At any rate, I am really happy that Apple is bringing more events online, hopefully we'll get firmware 1.1.3, local storage, and advanced WebKit CSS functionality in that update, or shortly thereafter.

Apple's original article is at:

http://developer.apple.com/documentation/AppleApplications/
Reference/SafariWebContent/HandlingEvents/chapter_8_section_6.html


  • visitor

    Thanks! it does work like a charm!