Window: resize event
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Theresize
event fires when the document view (window) has been resized.
This event is not cancelable and does not bubble.
In some earlier browsers it was possible to registerresize
event handlers on any HTML element. It is still possible to setonresize
attributes or useaddEventListener()
to set a handler on any element. However,resize
events are only fired on thewindow
object (i.e., returned bydocument.defaultView
). Only handlers registered on thewindow
object will receiveresize
events.
While theresize
event fires only for the window nowadays, you can get resize notifications for other elements using theResizeObserver API.
If the resize event is triggered too many times for your application, seeOptimizing window.onresize to control the time after which the event fires.
Syntax
Use the event name in methods likeaddEventListener()
, or set an event handler property.
addEventListener("resize", (event) => { })onresize = (event) => { }
Event type
A genericEvent
.
Examples
Window size logger
The following example reports the window size each time it is resized.
HTML
<p>Resize the browser window to fire the <code>resize</code> event.</p><p>Window height: <span></span></p><p>Window width: <span></span></p>
JavaScript
const heightOutput = document.querySelector("#height");const widthOutput = document.querySelector("#width");function reportWindowSize() { heightOutput.textContent = window.innerHeight; widthOutput.textContent = window.innerWidth;}window.onresize = reportWindowSize;
Result
Note:The example output here is in an<iframe>
, so the reported width and height values are for the<iframe>
, not the window that this page is in. In particular, it will be hard to adjust the window size so as to see a difference in the reported height.
The effect is easier to see if youview the example in its own window.
addEventListener equivalent
You could set up the event handler using theaddEventListener()
method:
window.addEventListener("resize", reportWindowSize);
Specifications
Specification |
---|
CSSOM View Module # eventdef-window-resize |