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?
Yup, via the onorientationchange
event and the window.orientation
property.
- Documented by Apple
- Example code on Ajaxian
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);