views:

1430

answers:

2

I’m writing a web site targeted at the iPhone. I’d like to set a class on the <body> element when the iPhone’s orientation changes (i.e. when the user turns the phone into landscape and/or portait mode).

Can I detect this change via JavaScript? Is there an event for this?

+12  A: 

Yup, via the onorientationchange event and the window.orientation property.

Paul D. Waite
That's also an elegant solution.
Thanks
FYI The login requirement for Apple's Safari Reference Library has been removed.
Pullets Forever
@Pullets Forever — ah, excellent, thank you. Updated accordingly.
Paul D. Waite
A: 

You could check the document body width. If it suddenly becomes smaller or bigger, you know what happened. You may measure it with an interval.

window.setInterval(function() {
    // check body with here and compare with global variable that holds the last measurement
    // you may set a boolean isLandscape = true if the body with became bigger.
}, 50);
Thanks
Not entirely sure that would work: `document.body.clientWidth` seems to return the same value in portrait and landscape (at least on the page I’m working on). There might be other properties you could check though.
Paul D. Waite
You would have to use something like getComputedStyle, and ask for the computed width of the body tag. If that doesn't work in the safari, try currentStyle. Also make sure that the body tag receives a width=100%.
Thanks
Yeah, that could work. It’s just that Mobile Safari’s notion of dimensions seems a bit abstract, because of the scaling it does with the iPhone’s screen. You don’t seem to actually get more pixel width (in terms of your layout) when it goes landscape, even though there are more physical pixels available.I haven’t actually checked what the various properties return though.
Paul D. Waite