Why changing device orientation won’t swap width and height?

We often need to perform script functions based on screen sizes of browser or get width and height on changing device orientation. There are numerous functions to get the width or height of a device or screen.

However, each are specific to either the device width or viewport width. Therefore, we should use the best function to get the browser width as per our requirements.

A common error faced by many developers is when with device orientation change, the height and width won’t swap. i.e. In portrait and landscape mode both, you get the width as 420px in your iPhone, whereas you expect it to be around 820px when in landscape mode. This effects many further operations and conditions based on device width. So, let’s get in depth of the nest window screen width function to use to get actual screen width even after device orientation.

window.innerWidth and window.outerWidth

To auto-detect varying width and height on changing device orientation, use of appropriate methods that measure the viewport width or height is preferred. Use of window.innerWidth and window.outerWidth detects the different width even in landscape mode, as these functions are measuring the viewport width instead of the actual device width.

Therefore, you can use window.innerWidth or window.outerWidth to measure the width of your screen, and window.innerHeight or window.outerHeight to measure the height. These methods will swap the width and height on device orientation change, and allow you to use appropriate functions as per your screen space.

There are even other functions to measure screen width and height. Namely, window.screen.height and window.screen.width are most commonly used. however, these won’t change values on orientation change or page resize, as they get you a device’s actual height and width, that cannot change.

orientationchange Event

You can use the orientationchange event to detect screen orientation change and read the swapped width and height values without reloading your page.

window.addEventListener('orientationchange', resizePage);

This event fires up whenever you change your screen. Therefore you can read varying dimensions and resize a div or the page based on this event.

Leave a Comment