We can use JavaScript to detect a window resize by using the addEventListener() method on the window object.

window.addEventListener("resize", function(event){
  //Do something when the user resizes the window
});

Let’s see a simple example of this below.


Let’s say we have the following JavaScript code:

window.addEventListener("resize", function(event){
  alert("The window has been resized.");
});

No matter what our HTML code is, the alert box will show if the user ever resizes their browser window. The function will also run every time the user resizes the window.

Let’s take a look at this for ourselves in the example below.

Using JavaScript to Detect User Window Resize

In this example, we will have a div with a background color. When we resize the window, we will change the color of our box div.

Here is our HTML setup:



Resize the window to change the color of the box.

Notice every time the box color changes when you drag the corner of the browser window to resize it.

When we resize the window, we will generate a random color and then change the background color of the div.

We will detect the window resize using the addEventListener() method.

Here is our JavaScript code:


//The genRandomColor function below will generate a random color for us
function genRandomColor() {
  var letters = '0123456789ABCDEF';
  var randomColor = '#';
  for (var i = 0; i < 6; i++) {
    randomColor += letters[Math.floor(Math.random() * 16)];
  }
  return randomColor;
}

//When a resizing of the browser is detected, the function below will run
//It will run every time the browser is resized.
window.addEventListener("resize", function(event){
  document.getElementById("div1").style.backgroundColor = genRandomColor();
});

The final code and output for this example of how to detect and change some HTML on window resize is below:

Code Output:

Resize the window to change the color of the box.

Notice every time the box color changes when you drag the corner of the browser window to resize it.

Full Code:



Resize the window to change the color of the box.

Notice every time the box color changes when you drag the corner of the browser window to resize it.

Hopefully this article has helped you to understand about JavaScript window resize.

Categorized in:

JavaScript,

Last Update: March 12, 2024