How to get the window width when it changes in JavaScript (width resize event)

In this article, you will learn how to use an event listener in Javascript to capture the width of the browser when the window resizes.

You might need to do this in order to run some JavaScript when the window shrinks or grows to a certain size.

The code is as follows:

window.addEventListener("resize", function() {
    if (window.innerWidth === 915) {
        
        // Do whatever you need to here;

    }
});

The way this works is using the resize event listener. This will run whenever the screen is resized (smaller or expanded).

Inside the event listener, you can run a function to execute some Javascript. In my particular example, if the screen size (the window.innerWidth) is 915 px, then I run some Javascript. Of course, you can put whatever width you want.