JavaScript Reference ยท DOM: Events
The resize event
Reference for the window resize event: read innerWidth and innerHeight, throttle handlers, and use ResizeObserver or matchMedia when you need more than the window.
The resize event fires on window when the size of the browser viewport changes: the user drags the window edge, rotates a phone, or opens developer tools docked to the side. It also fires on window.visualViewport when pinch-zoom or the on-screen keyboard changes the visible area.
Only the window (and visualViewport) fires resize. Ordinary elements do not, so to watch the size of a <div> you need a ResizeObserver. For layout changes at breakpoints, CSS media queries are usually enough and need no JavaScript.
window.addEventListener("resize", () => { console.log(window.innerWidth, window.innerHeight); });
Try it
Syntax
window.addEventListener("resize", listener); window.onresize = listener; window.visualViewport.addEventListener("resize", listener);
Size properties
| Name | Description |
|---|---|
window.innerWidth, innerHeight |
Viewport size in CSS pixels, including any scrollbar. |
document.documentElement.clientWidth |
Viewport width without the vertical scrollbar. |
window.outerWidth, outerHeight |
Size of the whole browser window, including toolbars. |
window.visualViewport.width, height, scale |
The currently visible area, which changes with pinch-zoom and the on-screen keyboard. |
The event is a plain UIEvent, is not cancelable, and does not bubble. It carries no size data; read the properties above.
Usage notes
- It fires very often while the user drags a window edge. Avoid layout work in the handler. Record a flag and update in
requestAnimationFrame(), as in the first example, or debounce withsetTimeout(). - Do not use it for breakpoints.
matchMedia("(min-width: 600px)")with achangelistener reports only when a breakpoint is crossed, and CSS handles most cases with no script. - Elements need
ResizeObserver. It also reports changes that are not window resizes: content that wraps, text-size changes, or elements shown and hidden. - Run the code once at start.
resizedoes not fire on load, so call your handler yourself to set the initial layout. - Mobile browsers. Showing or hiding the address bar changes the viewport height and can trigger
resizewhile scrolling. Do not reset scroll position or heavy state because of it. CSS unitsdvh,svhandlvhhandle most of these cases. - Zoom. Changing browser zoom changes
innerWidthin CSS pixels, so it also triggersresize. - Cleanup. In single-page apps, remove the listener when the component goes away, or use
{ signal }with anAbortController.
Browser support
The window resize event works in every browser. visualViewport and ResizeObserver are supported in all current browsers.