Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 322
Paul D. Waite Avatar asked May 11 '09 23:05

Paul D. Waite


People also ask

How can we detect the orientation of the screen?

You can detect this change in orientation on Android as well as iOS with the following code: var supportsOrientationChange = "onorientationchange" in window, orientationEvent = supportsOrientationChange ?

How do I get orientation in Javascript?

Detecting Orientation Changes in Javascript Should you need to simply detect when a user changes orientation, you can use the following event listener: screen. orientation. addEventListener("change", function(e) { // Do something on change });

Do iphones landscape mode?

The screen on your iPhone and iPod touch can rotate so that you can see apps — like Safari and Messages — in portrait or landscape mode.


2 Answers

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

  • Documented by Apple

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

like image 106
Paul D. Waite Avatar answered Oct 11 '22 07:10

Paul D. Waite


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);
like image 28
Thanks Avatar answered Oct 11 '22 08:10

Thanks