How do I detect when the iPhone goes into landscape mode via JavaScript? Is there an event for this?
Asked Answered
E

2

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?

Ernaldus answered 11/5, 2009 at 23:4 Comment(0)
E
26

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

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

Ernaldus answered 11/5, 2009 at 23:6 Comment(4)
That's also an elegant solution.Recline
FYI The login requirement for Apple's Safari Reference Library has been removed.Kutaisi
@Pullets Forever — ah, excellent, thank you. Updated accordingly.Ernaldus
ajaxian link broken :(Oldworld
R
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);
Recline answered 11/5, 2009 at 23:25 Comment(3)
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.Ernaldus
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%.Recline
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.Ernaldus

© 2022 - 2024 — McMap. All rights reserved.