Menacing Cloud

Orientation Correct Screen Width

The following code demonstrates a simple approach to getting the screen width, taking into account the current device orientation.

I use the following code to get the orientation. The containing class will be demonstrated in future articles, so I kept this format.

// Update viewport orientation //----------------------------- this.updateOrientation = function() { this.orientation = window.orientation; if(this.orientation === 0 || this.orientation === 180) this.orientation = 'portrait'; else if(this.orientation === 90 || this.orientation === -90) this.orientation = 'landscape'; else { // JavaScript orientation not supported. Work it out. if(document.documentElement.clientWidth > document.documentElement.clientHeight) this.orientation = 'landscape'; else this.orientation = 'portrait'; } };

If orientation is not directly supported, we are taking an educated guess based on the viewport dimensions.

This allows us to work out the corrected screen width.

// Update screen width //--------------------- this.updateScreenWidth = function() { this.screenWidth = screen.width; if(this.orientation === 'portrait') { // Take smaller of the two dimensions if(screen.width > screen.height) this.screenWidth = screen.height; } else { // Landscape. Take larger of the two dimensions. if(screen.width < screen.height) this.screenWidth = screen.height; } };


Comments, suggestions or feedback via Optic Swerve on Twitter please.

Follow the author on Twitter.

ProtoFluid. ‘Effortless responsive web design testing’.

Previous Articles

Canvas Generated Icons. Read more.

Targeting Windows 8 Snap Mode. Read more.

CSS @viewport rule or viewport meta tag? Read more.

The Responsive Viewport. Missing piece of the responsive web design puzzle? Read more.

Getting the Viewport Scale.
Read more.

Hiding the iPhone Address Bar.
Read more.

Orientation Correct Screen Width.
Read more.

iPhone Title Modification.
Read more.

Optimising for High Pixel Density Displays.
Read more.

CSS3 Media Query Prototyping With ProtoFluid.
Read more.

AJAX Kill Switch. Version 2.
Read more.

URI Processing With JavaScript.
Read more.

Source Code

All source code is provided for free.

A standard disclaimer of warranty and limitation of liability applies.