Skip to content
the poor coder

track window size js

Poor Man
Published
Reading time
1 min read
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.

Text
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.

Text
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC