HTML onresize Attribute

Beginner
⏱️ 6 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onresize attribute is an inline event handler for the resize event on the window. It runs when the user resizes the browser viewport — useful for updating layout labels, repositioning charts, or syncing JavaScript widgets with the new width and height. Read window.innerWidth and window.innerHeight inside your handler. Put onresize on <body> or use window.addEventListener("resize", …). Debounce heavy work because resize fires many times per drag. For individual elements, use ResizeObserver instead. Prefer CSS media queries when possible.

What You’ll Learn

01

Event handler

Inline JS.

02

resize

Window size.

03

window / body

Global scope.

04

innerWidth

Viewport px.

05

Debounce

Performance.

06

addEventListener

Preferred way.

Purpose of onresize Attribute

The primary purpose of onresize is to react when the browser window changes size — so JavaScript-driven layouts can adapt when CSS alone is not enough (for example redrawing a canvas chart or updating a custom breakpoint label).

The resize event fires on the window object. It does not fire for every DOM element when that element changes size — for that, use the ResizeObserver API in modern browsers.

💡
Prefer CSS when you can

Media queries and flexible layouts handle most responsive design without JavaScript. Use onresize when JS must recalculate sizes — charts, maps, or custom components.

📝 Syntax

Set onresize on body or assign window.onresize in JavaScript:

onresize.html
<body onresize="handleResize()"></body>

<script>
  window.onresize = handleResize;
  window.addEventListener("resize", handleResize);
</script>

Syntax Rules

  • Value is JavaScript executed when the resize event fires on the window.
  • Valid on <body> as a window event content attribute.
  • Also assignable as window.onresize in script.
  • Fires repeatedly while the user drags the window edge — debounce heavy logic.
  • Read window.innerWidth / innerHeight for viewport size.
  • Modern alternative: window.addEventListener("resize", handler).
  • Not for random <div> elements — use ResizeObserver instead.

💎 Values

The onresize attribute accepts a string of JavaScript code:

  • onresize="handleResize()" — Call a named function.
  • onresize="updateChart()" — Redraw JS widgets on resize.
  • JavaScript: window.onresize = () => { … } — property assignment.
onresize-handler.html
var timer;
function handleResize() {
  clearTimeout(timer);
  timer = setTimeout(function () {
    status.textContent =
      window.innerWidth + " × " + window.innerHeight + " px";
  }, 150);
}

window.addEventListener("resize", handleResize);

⚡ Quick Reference

Property / APIWhen it runsNotes
resizeWindow viewport changesonresize
window.innerWidthRead anytimeViewport width in px
window.innerHeightRead anytimeViewport height in px
matchMedia()Breakpoint checksOften better than resize
ResizeObserverElement size changesNot onresize attribute

Applicable Elements

TargetSupported?Notes
<body>YesWindow event on body (HTML)
windowYesPrimary target in JavaScript
<iframe>Yes (legacy)Frame resize in some cases
<div>, <section>NoUse ResizeObserver
CSS @mediaRelatedPrefer for layout when possible

onresize vs matchMedia vs ResizeObserver

APIWhat it watchesTypical use
onresizeBrowser window viewportCharts, full-page JS layout
matchMedia()CSS media query matchBreakpoint toggles
ResizeObserverSpecific element sizeComponent layouts
CSS @mediaViewport width/heightResponsive styling

Examples Gallery

Inline body handler, dynamic assignment, and a debounced breakpoint label with addEventListener.

👀 Live Preview

Resize your browser window — dimensions update below:

Loading…

Example — onresize on body

Show viewport dimensions when the window is resized:

body-onresize.html
<body onresize="handleResize()">
  <p id="size"></p>
</body>

<script>
  function handleResize() {
    document.getElementById("size").textContent =
      window.innerWidth + " × " + window.innerHeight + " px";
  }
  handleResize();
</script>
Try It Yourself

How It Works

The browser fires resize on the window when the viewport changes. The body attribute runs handleResize() each time.

Dynamic Values with JavaScript

Assign the handler on window at runtime:

dynamic-onresize.html
<script>
  window.onresize = function () {
    log.textContent =
      "Resized to " + window.innerWidth + " × " + window.innerHeight;
  };
</script>
Try It Yourself

How It Works

Assigning window.onresize is equivalent to the inline body attribute for the resize event.

Example — Debounced breakpoint label

Wait until resizing stops before running expensive layout logic:

debounced-resize.html
var timer;
window.addEventListener("resize", function () {
  clearTimeout(timer);
  timer = setTimeout(function () {
    var w = window.innerWidth;
    status.textContent = getBreakpoint(w) + " — " + w + " px";
  }, 150);
});
Try It Yourself

How It Works

Resize fires dozens of times per second while dragging. A 150ms debounce runs your logic once after the user pauses.

♿ Accessibility

  • Do not break zoom — Never block browser zoom; users rely on it for readability.
  • Content reflow — Ensure resized layouts keep reading order and focus paths logical.
  • Avoid layout shift — Debounced JS updates should not jump focus unexpectedly.
  • Test keyboard users — Resizing should not trap focus or hide controls.
  • Prefer responsive CSS — Media queries scale text and spacing without JS — better for all users.

🧠 How onresize Works

1

User resizes window

Drag edge.

Viewport
2

resize fires

onresize runs.

Event
3

Read dimensions

innerWidth.

Layout
=

Adapt UI

Redraw / relabel.

Browser Support

The resize event and onresize handler are supported in all modern browsers, including Internet Explorer 9+.

Window Events · Fully supported

Universal onresize support

All major browsers fire resize when the viewport changes size.

99% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer IE 9+ supported
Full support
Opera Fully supported
Full support
onresize attribute 99% supported

Bottom line: Reliable for window resize handling in all modern browsers.

💡 Best Practices

✅ Do

  • Debounce or throttle resize handlers
  • Use CSS media queries for layout when possible
  • Read innerWidth / innerHeight for viewport size
  • Use addEventListener("resize", …) in production
  • Use ResizeObserver for element-level sizing

❌ Don’t

  • Use alert() on every resize
  • Put onresize on random divs
  • Run heavy DOM work on every pixel change
  • Rely on resize for mobile orientation — use media queries
  • Assume resize detects element size changes

Conclusion

The onresize attribute runs JavaScript when the browser window changes size — useful for charts, custom breakpoints, and JS-driven layouts that CSS alone cannot handle.

Debounce your handlers, prefer CSS for styling, use addEventListener in production, and reach for ResizeObserver when you need element-level size changes.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onresize

Bookmark these before wiring resize logic.

5
Core concepts
📈 02

Debounce

Performance.

Pattern
🔎 03

innerWidth

Read px.

API
🎨 04

CSS first

@media.

Prefer
05

Not elements

ResizeObserver.

Gotcha

❓ Frequently Asked Questions

It runs JavaScript when the resize event fires on the window — when the user changes the browser viewport size.
No. onresize is for the window (via body or window). Use ResizeObserver to watch when a specific element changes size.
Resize fires many times per second while dragging. Debouncing waits until the user pauses — avoiding jank and wasted CPU.
onresize runs on every viewport change. matchMedia checks whether a CSS media query matches — often cleaner for breakpoint toggles.
window.addEventListener("resize", handler) is preferred in production — easier to debounce and attach multiple listeners.
Yes in all modern browsers; Internet Explorer 9+.

Build responsive JavaScript layouts

Practice the onresize attribute with dimension display and debounced breakpoints in the Try It editor.

Try onresize demo →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful