Get window width in vanilla JavaScript Vanilla JS

It can be useful to get the user's window width with JavaScript and run code if the window width is larger or smaller than a certain value. You can also add an event listener for the window resize event in JavaScript and then check the window width on resize. This is how to get the window width in vanilla JavaScript.

let width = window.innerWidth;

This gets the window width and stores the value in a variable. It might be more useful to create a conditional statement to check if the window width is greater or less than a specific value. This is how to check if the window width is smaller or larger than a certain value.

if (window.innerWidth < 900) {
} else {

The width value you check against is in device-independent pixels and is written without the "px" unit.

That works for the initial width when the page first loads, but you also need to account for when the window is resized. If you don't check for a resize event then any changes you make with JavaScript depending on the window width will only be applied based on the initial width and not the final width if a user resizes their window/viewport.

To check the window width on resize, you can wrap your conditional statement inside a 'resize' event listener. This is how to get the window width after a resize event in vanilla JavaScript.

window.addEventListener('resize', function() {
    let win = this;
    if (win.innerWidth < 900) {
    } else {

You most likely won't be using just the resize code block alone without also getting the initial width with the first code block otherwise your changes will only apply if there is a resize event and not otherwise. So you'll likely want to use both of these conditional statement code blocks and place your changes that happen with JavaScript based on the window/viewport width inside both of them.

Thanks for reading.

Published on 22 Mar 2019 (on a previous domain)
Last modified on 5 Aug 2022