How to Get the Screen Width in Javascript


Javascript gives a few options to determine the screen width.

When we say screen, we mean the browser window’s width itself.

Option 1 – Using Native Javascript

Using native Javascript objects, we can find the innerWidth and innerHeight:

var w = window.innerWidth;
var h = window.innerHeight;

The window object also allows for:

window.screen.width
// or simply
screen.width

We can write some code to tell us the width and height with fallbacks:

var win = window,
    doc = document,
    docElem = doc.documentElement,
    body = doc.getElementsByTagName('body')[0],
    x = win.innerWidth || docElem.clientWidth || body.clientWidth,
    y = win.innerHeight|| docElem.clientHeight|| body.clientHeight;
alert(x + ' × ' + y);

Option 2 – Get Width using jQuery

$(window).width()

You can use this as follows:

if ($(window).width() < 960) {
   alert('Less than 960');
} else {
   alert('More than 960');
}