Skip to content

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;
Code language: JavaScript (javascript)

The window object also allows for:

window.screen.width // or simply screen.width
Code language: JavaScript (javascript)

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')[], x = win.innerWidth || docElem.clientWidth || body.clientWidth, y = win.innerHeight|| docElem.clientHeight|| body.clientHeight; alert(x + ' × ' + y);
Code language: JavaScript (javascript)

Option 2 – Get Width using jQuery

$(window).width()
Code language: JavaScript (javascript)

You can use this as follows:

if ($(window).width() < 960) { alert('Less than 960'); } else { alert('More than 960'); }
Code language: JavaScript (javascript)

See also  How to Convert a Number to a String in Java
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x