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

19,080

Solution 1

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

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

Solution 2

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);
Share:
19,080
Joe Dargie
Author by

Joe Dargie

Freelance web developer in London.

Updated on June 05, 2022

Comments

  • Joe Dargie
    Joe Dargie almost 2 years

    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?