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 (sent to) the window object (i.e. returned by document.defaultView). Only handlers registered on the window object will receive resize events.

There is a new proposal (2017) 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.

Examples

You can register an event handler for the resize event using either window.onresize or window.addEventListener('resize', ...).

Since resize events can fire at a high rate, the event handler shouldn't execute computationally expensive operations such as DOM modifications. Instead, it is recommended to throttle the event using setTimeout() or requestAnimationFrame(). Below, you can find an example using setTimeout().

setTimeout

const delay = 100;  // Your delay here

const originalResize = evt => {
  console.log(evt);  // Your resize function here
};


(() => {
  resizeTaskId = null;

  window.addEventListener('resize', evt => {
    if (resizeTaskId !== null) {
      clearTimeout(resizeTaskId);
    }

    resizeTaskId = setTimeout(() => {
      resizeTaskId = null;
      originalResize(evt);
    }, delay);
  });
})();

Specifications

Specification Status
Document Object Model (DOM) Level 3 Events Specification
The definition of 'resize' in that specification.
Obsolete
CSS Object Model (CSSOM)
The definition of 'resize' in that specification.
Working Draft

Browser compatibility

No compatibility data found. Please contribute data for "api.Document.defaultView.resize" (depth: 1) to the MDN compatibility data repository.

See also