track window size js
- Published
- Reading time
- 1 min read
- Length
- 233 words
On this page
How to Track Window Size in JavaScript#
If you want to track the window size of a user's browser, you can use JavaScript to do so. This can be helpful for responsive design or for any other situation where you need to know the dimensions of the user's viewport.
Method 1: Using window.innerWidth and window.innerHeight#
The most common way to get the dimensions of the user's viewport is to use the window.innerWidth and window.innerHeight properties. These properties return the width and height of the viewport in pixels, respectively.
var width = window.innerWidth;
var height = window.innerHeight;
document.getElementById("dimensions").innerHTML = "Width: " + width + " Height: " + height;This code will get the width and height of the viewport and display them on the page. You can replace document.getElementById("dimensions") with any other element on your page where you want to display the dimensions.
Method 2: Using window.onresize#
If you want to track changes in the size of the viewport as the user resizes their browser window, you can use the window.onresize event.
window.onresize = function(event) {
var width = window.innerWidth;
var height = window.innerHeight;
document.getElementById("dimensions").innerHTML = "Width: " + width + " Height: " + height;
};This code will update the dimensions on the page every time the browser window is resized. Again, you can replace document.getElementById("dimensions") with any other element on your page where you want to display the dimensions.