How to get the Width and Height of Browser's Viewport in JavaScript
Table of Contents
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.
JAVASCRIPTconst width = window.innerWidth;
const height = window.innerHeight;
console.log(`The viewport's width is ${width} and the height is ${height}.`);
BASHThe 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.
JAVASCRIPTwindow.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!
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Learn how to build a Slack Bot using Node.js
- Getting Started with Vuex: Managing State in Vue