Window: resize event

The resize event fires when the document view (window) has been resized.

Bubbles No
Cancelable No
Interface UIEvent
Event handler property onresize

In some earlier browsers it was possible to register resize event handlers on any HTML element. It is still possible to set onresize attributes or use addEventListener() to set a handler on any element. However, resize events are only fired on the window object (i.e. returned by document.defaultView). Only handlers registered on the window object will receive resize events.

There is a proposal to allow all elements to be notified of resize changes. See Resize Observer to read the draft document, and GitHub issues to read the on-going discussions.

If the resize event is triggered too many times for your application, see Optimizing window.onresize to control the time after which the event fires.

Examples

Window size logger

The following example reports the window size each time it is resized. Bear in mind that since the example is running in an <iframe>, you'll need to actually get the <iframe> to resize before you see an effect.

<p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>
const heightOutput = document.querySelector('#height');
const widthOutput = document.querySelector('#width');

function reportWindowSize() {
  heightOutput.textContent = window.innerHeight;
  widthOutput.textContent = window.innerWidth;
}

window.onresize = reportWindowSize;

addEventListener equivalent

You could set up the event handler using the addEventListener() method:

window.addEventListener('resize', reportWindowSize);

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari WebView Android Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet
resize_event
1
Chrome does not emit a resize event on page load.
12
Before Edge 79, Edge emitted a resize event on page load. This is no longer the case.
1
Before Firefox 68, Firefox emitted a resize event on page load. This is no longer the case.
4
7
Opera does not emit a resize event on page load.
1.1
1
Webview does not emit a resize event on page load.
18
Chrome does not emit a resize event on page load.
4
Before Firefox 68, Firefox emitted a resize event on page load. This is no longer the case.
10.1
Opera does not emit a resize event on page load.
1
1.0
Samsung Internet does not emit a resize event on page load.

See also

© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event