How to get the device width and height with JavaScript

Here's a useful snippet for those who work with responsive designs. CSS Media Queries are cool and all but when you need it with JavaScript, here's how to do it:

var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
var height = (window.innerHeight > 0) ? window.innerHeight : screen.height;

Viewport meta tag

You should also have this meta tag in your head section, this will give you a better experience on mobile browsers:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Learn more about the Viewport meta tag.

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*