The “resize” event in JavaScript is a built-in event triggered when the user changes the size of a browser window. This event can be used to adjust the layout or behavior of a web page in response to the new window size. The event is triggered/fired on the window object that denotes the browser window.
This post will illustrate the Window resize event in JavaScript.
What is the Window “resize” Event in JavaScript?
In JavaScript, the “resize” event is fired when the browser window size changes. You can attach a function to the resize event using the “addEventListener()” method on the window object. This event will trigger whenever the browser window is resized.
Syntax
The following syntax is used for the resize event for resizing the window with the “addEventListener()” method:
It is recommended to remove the event listener to avoid any memory leaks. For removing the event listener, use the “removeEventListener()” method:
Example
In the provided example, the length and the width of the window will display on the page while resizing the window.
First, create a span area for displaying the length and width of the window:
Window's Height:<span id="height"></span>
Then, in <script> tag, define a function “windowResize()” where get the reference of the length and width elements to print the values:
document.getElementById('height').innerText=document.documentElement.clientHeight;
document.getElementById('width').innerText = document.documentElement.clientWidth;
}
Call the “resize” event in the “addEventListener()” method and attach the defined function with the event:
Call the “windowResize()” for the first time:
The output indicates that the value is continuously changed while changing the window size:
That’s all about the window resize event in JavaScript.
Conclusion
The “resize” event in JavaScript is triggered when the size of a window or an element is changed. It can detect changes to the browser window’s size or a specific element. The event can be added to a window or element using the “addEventListener()” method and specifying “resize” as the event type. In this post, we illustrated the Window resize event in JavaScript.