Account
Categories

JavaScript onresize Event: Window Resize


Definition

When you use this event on a webpage, the user can adjust the page size by dragging it.

It changes the page layout, content, or style automatically when the user resizes the window.

This action is done by the user, who can resize the window, while the developer decides how the page elements change.

It is called the onresize event.

Now you will clearly understand with the help of the flowchart.

Start
   |
   v
User opens the webpage
   |
   v
The browser shows the page
   |
   v
User resizes the browser window
   |
   v
onresize Event runs
   |
   v
Check what should change:
   |-- Layout --> Adjust layout
   |-- Content --> Adjust content
   |-- Styles --> Adjust styles
   |
   v
Page elements update automatically
   |
   v
End
  

Syntax:

In HTML:

<body onresize="myFunction()">

In JavaScript:

window.onresize = myFunction;

Example:

<!DOCTYPE html>
<html>
<body onresize="resizeMessage()">

<h2>Resize the Window Example</h2>
<p>Try to resize this browser window.</p>

<script>
// This function runs whenever the user resizes the window.
function resizeMessage() {
  alert("You resized the window!");
}
</script>

</body>
</html>