How to get the Screen Width in Javascript

0 min read 132 words

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');
}
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts