CKTIS / JavaScript
Window `resize` event
Listen for `resize` on `window` to respond to layout viewport size changes. Use `ResizeObserver` when you need to track the size of an individual element.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
window.addEventListener("resize", handler);
window.removeEventListener("resize", handler);
// Alternative: assign a single handler property.
window.onresize = handler;
window.onresize = null;The Window.resize event is fired by the browser on window when the layout viewport changes size. This is a web platform API, not part of ECMAScript. The browser delivers a plain Event with no new dimensions on it. The event does not bubble, and preventDefault() cannot cancel it.
Read the current width and height from window.innerWidth and window.innerHeight. These values are in CSS pixels and include the vertical scrollbar's width and horizontal scrollbar's height, respectively, if present. If your app needs the dimensions immediately, call your update function during setup: registering a listener does not call it. Resizing can trigger the event repeatedly, so avoid expensive work on every call.
Use addEventListener("resize", handler) to allow multiple distinct listeners. When a listener is no longer needed, remove it with removeEventListener() using the same event type, function reference, and capture value. Assigning to window.onresize replaces only the handler set through that property, not listeners added with addEventListener(); assigning null clears the property handler.
Use ResizeObserver to watch an individual element: an element can change size without a layout viewport resize. To track the size of the visible part of the page, listen for the separate resize event on window.visualViewport where that API is available.
Examples
{
const target = typeof window === "undefined" ? new EventTarget() : window;
function reportResize(event) {
console.log(`${event.type}: bubbles=${event.bubbles}, cancelable=${event.cancelable}`);
}
target.addEventListener("resize", reportResize);
target.dispatchEvent(new Event("resize"));
target.removeEventListener("resize", reportResize);
target.dispatchEvent(new Event("resize"));
}Result
resize: bubbles=false, cancelable=false
Run this in a browser console or in Node.js 24. The browser uses `window`; Node.js uses a standalone `EventTarget`. The first synthetic event calls the listener synchronously and logs one line. The second is dispatched after removal, so the snippet logs nothing more. Neither dispatch changes the viewport size.
Related lessons
- JavaScript · Lesson 27 · Intermediate · Version: 3