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?
You can detect this change in orientation on Android as well as iOS with the following code: var supportsOrientationChange = "onorientationchange" in window, orientationEvent = supportsOrientationChange ?
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 });
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.
Yup, via the onorientationchange
event and the window.orientation
property.
(On platforms other than iOS, the ScreenOrientation
API is used instead.)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With