Categories
JavaScript Answers

How to Get the Size of the Screen, Current Web Page, or Browser Window with JavaScript?

Spread the love

Getting the screen size is important if we want to create responsive web apps.

Therefore, this is an operation that’s frequently done within JavaScript web apps.

In this article, we’ll look at how to get the size of the screen, web page, or browser window with JavaScript.

Use the window.screen Object to Get a Screen’s Dimensions

The window.screen object lets us get the height and width of the browser’s screen with the height and width properties respectively.

For instance, we can write:

console.log(window.screen.height,
  window.screen.width)

to get the height and width of the screen that the app is currently on.

Window innerWidth and innerHeight Properties

The window.innerWidth and window.innerHeight properties let us get the current width and height of the frame that the app is currently being displayed in.

It doesn’t include dimensions of anything outside the frame like toolbars, etc.

For instance, we can write:

console.log(window.innerWidth, window.innerWidth)

log both the width and the height of the frame.

Window outerWidth and outerHeight Properties

The window.outerWidth and window.outerHeight properties let us get the current width and height of the frame that the app is currently being displayed in.

It includes dimensions of the whole frame including the toolbars and scrollbars.

For instance, we can write:

console.log(window.innerWidth, window.innerWidth)

log both the width and the height of the frame with the toolbars and scrollbars.

Use the window.screen Object to Get the Available Space of the Screen

We can use the window.screen object to get the available space of the screen with the availWidth and availHeight properties.

For instance, we can write:

console.log(window.screen.availWidth, window.screen.availHeight)

to get the available width and height of the screen that’s available to the browser.

So the operating system’s menubars and taskbars dimensions will be subtracted from the screen’s resolution.

Get Screen Dimensions From the document Object

Also, we can get the screen’s dimensions from the document object.

For instance, we can write:

console.log(document.body.clientWidth, document.body.clientHeight)

to get the width and height of the body element.

clientWidth is calculated from the CSS width +CSS padding — height of the vertical scrollbar.

clientHeight is calculated from the CSS height +CSS padding — height of the horizontal scrollbar.

Conclusion

There are several ways to get the dimensions of the screen or the browser window with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *