While detecting screen orientation and changes in Safari on iPhones using JavaScript is possible, is it also feasible on Android phones?
Responsive Rotation Detection on Android
In Android phones, rotation detection using JavaScript is a complex matter due to the varying behaviors across devices and browsers. Relying solely on the resize or orientationchange events is unreliable.
Reliable Approach
The recommended approach involves monitoring both resize and orientationchange events, consistently checking for orientation updates through polling intervals.
<code class="javascript">var previousOrientation = window.orientation; var checkOrientation = function(){ if(window.orientation !== previousOrientation){ previousOrientation = window.orientation; // orientation changed, do your magic here } }; window.addEventListener("resize", checkOrientation, false); window.addEventListener("orientationchange", checkOrientation, false); // (optional) Android doesn't always fire orientationChange on 180 degree turns setInterval(checkOrientation, 2000);</code>
Device Specific Behavior
Device responses to orientation changes vary significantly. Here's a table of event sequencing and values obtained from testing four different devices:
Device | Events Fired | orientation | innerWidth | screen.width |
---|---|---|---|---|
iPad 2 (to landscape) | resize, orientationchange | 0 | 1024 | 768 |
iPad 2 (to portrait) | resize, orientationchange | 90 | 768 | 768 |
iPhone 4 (to landscape) | resize, orientationchange | 0 | 480 | 320 |
iPhone 4 (to portrait) | resize, orientationchange | 90 | 320 | 320 |
Droid phone (to landscape) | orientationchange, resize | 90 | 320 | 320 |
Droid phone (to portrait) | resize, orientationchange, resize | 0 | 569 | 569 |
Samsung Galaxy Tablet (to landscape) | orientationchange, orientationchange, resize | 0 | 400 | 400 |
Samsung Galaxy Tablet (to portrait) | orientationchange, orientationchange, orientationchange, resize | 90 | 683 | 683 |
Conclusion
While event handling for orientation changes may differ between iOS and Android devices, employing the recommended approach ensures reliable orientation detection on Android phones using JavaScript.
The above is the detailed content of How Can You Reliably Detect Android Phone Rotation in Browsers Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!