Explain Codes LogoExplain Codes Logo

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

javascript
orientation-change
event-listening
responsive-design
Nikita BarsukovbyNikita Barsukov·Jan 8, 2025
TLDR
// Detect portrait orientation like Sherlock Holmes detecting clues if(window.matchMedia("(orientation: portrait)").matches) { alert("Sherlock says: Rotate your device for a better view, Watson!"); }

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.

window.addEventListener('orientationchange', function() { if(window.matchMedia("(orientation: portrait)").matches) { alert("Flip me like one of your French phones for a better view!"); } });

Leveraging custom utility functions

Define isPortrait() and isLandscape() utility functions for clear code that's easy to read.

function isPortrait() { // Check if height is greater than width just like skyscrapers in a city skyline return window.innerHeight > window.innerWidth; } function isLandscape() { // Check if width is greater than height, kinda like a pancake return window.innerWidth > window.innerHeight; } if (isPortrait()) { alert("Rotate me for a pancake view. Yum!"); }

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.

function hasKeyboard() { // Check if there's a keyboard spoiling our fun return window.innerHeight < screen.availHeight; } if (isPortrait() && !hasKeyboard()) { alert("Rotate for a mind-boggling wide view!"); }

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.