Let’s see how to do this.
// storing width and height values in variables
var width = window.innerWidth;
var height = window.innerHeight;
// code to display viewport width and height on screen
document.write(width + " x " + height);
The code will show the current width and height of your browser window. The output on my laptop is shown below, however, your browser window size might be different in that case you will see different values.
Note: The width and height values are in pixels.
Moreover, the above code will show the fixed viewport width and height of the current screen or window. But what if you resize your browser window? Then, the values remain the same. But you might expect the change. Here we recommend another appropriate way that will dynamically update the values of width and height if you resize your browser screen.
// creating a function to handle viewport change
document.write(window.innerWidth + " x " + window.innerHeight);
// Adding eventlistner for window resize
// Calling viewportHandler() function when resize occurs
- First, I created a function that will be called when the resize event occurs.
- Then, I added the event listener for window resizing.
- And the last line of code will make a function call when the event will occur.
Note: After resizing your browser window, you have to refresh the web page to see the output.
- It empowers front-end developers to create responsive web designs by checking the width and height of different screen sizes of any device.
- You can precisely position elements.
- Utilize media queries effectively, and enhance user interaction.
- By accessing the viewport width and height, you can adapt your website layout and content dynamically, ensuring optimal presentation across different devices and screen resolutions.
Help others by sharing this tutorial!