Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions
Ways to effectively listen for orientation change
Let's explore 3 prevalent methods to listen and take actions on orientation change:
Using the orientationchange event
Listen for an orientationchange and handle it in real-time with your custom function, which could be showing an informative alert to the user.
Leveraging custom utility functions
Define isPortrait()
and isLandscape()
utility functions for clear code that's easy to read.
Handling browser compatibility
Remember that window.orientation
is deprecated in some browsers. Thus, it's a best practice to use window.matchMedia
for better browser compliance.
Caveats and considerations
Detecting orientation has some noisy neighbors that can complicate the process:
- Digital keyboards can affect the viewable screen area.
- Rapid orientation changes need some debouncing to avoid an event storm.
Strategies for resilient orientation detection
Managing the keyboard factor
Digital keyboards can cause wrong orientation detection. To handle, compare screen.availHeight
and screen.availWidth
, which stay steady.
Balancing between CSS media queries and JavaScript
CSS3 media queries excel at layout adaptation but lack the triggering power of JavaScript. Join their forces for a powerful balance.
Testing on various devices
Testing on multiple devices is crucial to ensure your JS doesn't pull a diva moment on some obscure smartphone brand.
Was this article helpful?