15

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 portrait mode).

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

Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270

2 Answers2

26

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

(On platforms other than iOS, the ScreenOrientation API is used instead.)

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
1

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);
Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
Thanks
  • 40,109
  • 71
  • 208
  • 322
  • 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 May 11 '09 at 23:50
  • 1
    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 May 12 '09 at 08:30
  • 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 May 12 '09 at 09:22