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
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a Deno app using Docker
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Getting User Location using JavaScript's Geolocation API