How to get the Width and Height of Browser's Viewport in JavaScript

Updated onbyAlan Morel
How to get the Width and Height of Browser's Viewport in JavaScript

The browser is the program that takes your HTML, CSS, and JavaScript, and renders it on the screen.

With that being said, the actual size of the canvas is going to be different depending on the screen size, browser, device type, and other factors.

For example, mobile phones will have a smaller viewport than desktop computers.

Because of this, as front-end developers, we need a way to get the size of the viewport of the browser so we can use it in things like calculations and position.

In this post, we'll learn the best way to get the viewport using JavaScript.

Getting the Viewport size using JavaScript

To get the width and height of a viewport, we can use the innerWidth and innerHeight properties of the window object.

The window property has a lot of useful properties and methods that we can use to get information about the browser, including the viewport's width and height.

Here's an example of how we can use these properties to get the viewport's width and height.

JAVASCRIPT
const width = window.innerWidth; const height = window.innerHeight; console.log(`The viewport's width is ${width} and the height is ${height}.`);
BASH
The viewport's width is 1920 and the height is 1080.

Keep in mind that this value will change if the browser is resized, so if you need the values, you'll need to get them every time you need them.

Alternatively, you can also attach an event listener so you can run some code when the viewport's size changes.

JAVASCRIPT
window.addEventListener("resize", () => { const width = window.innerWidth; const height = window.innerHeight; console.log(`The viewport's width is ${width} and the height is ${height}.`); });

Conclusion

In this post, we learned at how to get the viewport's width and height using JavaScript.

Just read the innerWidth and innerHeight properties of the window object to get the viewport's width and height.

Hopefully, this has been useful to you. Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.