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!
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js