jQuery / Method / .resize() - Handle Window Size Changes
Use $(window).on("resize", handler) to run work when the browser window changes size. The shorthand .resize(handler) has been deprecated since jQuery 3.3, so use .on() in new code. If the same work is needed initially, call the update function once instead of waiting for a resize.
The resize event versus its shorthand
The jQuery resize event registers a handler on window. Deprecating the .resize() shorthand does not deprecate the event itself. The tested full builds 3.7.1 and 4.0.0 still contain the shorthand; .on("resize", …) makes registration and cleanup explicit.
The native window resize event does not bubble, and changing a div’s width does not automatically emit resize on that div. Consider ResizeObserver for changes to an element’s own dimensions. Window resizing may produce repeated events, so do not rely on an exact invocation count.
Complete example with initialization, debounce and cleanup
Save all code as UTF-8 in resize-demo.html and open it in a browser. Internet is needed for the official jQuery file 4.0.0 from its content delivery network (CDN), with no installation. These interactions were executed with jQuery 3.7.1 and 4.0.0 in Edge on Windows, changing the viewport dimensions.
Debounce cancels the previous timer on repeated notifications, updating 150ms after the last one. Browser scheduling can delay actual execution further. The example reports narrow/wide around 600 CSS pixels; a CSS media query controls the sample’s border.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Window resize with debounce and cleanup</title>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<style>
body { font: 16px/1.6 sans-serif; max-width: 760px; margin: 24px auto; padding: 16px; }
button { font: inherit; margin: 4px; max-width: 100%; }
#sample { padding: 16px; background: #edf9f6; border: 1px solid teal; }
pre { white-space: pre-wrap; overflow-wrap: anywhere; }
@media (min-width: 600px) { #sample { border-width: 3px; } }
</style>
</head>
<body>
<h1>Observe window resize</h1>
<button type="button" id="trigger">Trigger resize notification</button>
<button type="button" id="stop">Stop listener</button>
<button type="button" id="start">Start listener</button>
<button type="button" id="reset">Reset counters</button>
<div id="sample">Resize the browser or responsive preview.</div>
<pre id="result" aria-live="polite"></pre>
<script>
$(function () {
let timer = null, active = false, events = 0, renders = 0;
function render() {
renders++;
const width = window.innerWidth;
const height = window.innerHeight;
$("#result").text(`viewport=${width} x ${height}\nmode=${width < 600 ? "narrow" : "wide"}\nlistener=${active ? "on" : "off"}\nresize events=${events}\nrenders=${renders}`);
}
function changed() {
events++;
clearTimeout(timer);
timer = setTimeout(function () { timer = null; render(); }, 150);
}
function detach() {
$(window).off("resize.windowLesson");
clearTimeout(timer); timer = null; active = false;
}
function attach() {
detach();
$(window).on("resize.windowLesson", changed);
active = true;
render();
}
$("#trigger").on("click", function () { $(window).trigger("resize"); });
$("#stop").on("click", function () { detach(); render(); });
$("#start").on("click", attach);
$("#reset").on("click", function () { detach(); events = 0; renders = 0; attach(); });
attach();
});
</script>
</body>
</html>
This initial output assumes a viewport of 390×844 CSS pixels. Your dimensions will differ, and mode is wide at widths of 600 or more. resize events=0 with renders=1 shows that initialization called the update function directly.
viewport=390 x 844
mode=narrow
listener=on
resize events=0
renders=1
- Change the browser size or responsive developer preview. After stopping, check that viewport shows the final dimensions. resize events counts notifications; renders counts updates.
- Trigger resize notification sends only a notification. Event and delayed render counts increase without changing the window dimensions.
- Stop listener sets listener=off. Subsequent resizing leaves the output unchanged. It also cancels the pending timer, preventing a late update.
- Start listener remeasures the current dimensions. It removes the old handler before registration, so repeated presses retain only one own handler.
- Reset counters restores zero events and one render at the current window size, then resumes listening. It does not resize the browser back to 390×844.
Stopping work differs from restoring actual window dimensions. Keep dimensions unchanged and press the notification button to compare events with physical resizing. Three notifications sent synchronously in testing produced three events and one delayed update; that does not fix the count for real mouse-driven resizing.
Prevent duplicate registration and delayed work
The resize.windowLesson namespace identifies this example’s handler. .off("resize.windowLesson") differs from .off("resize"), which would remove other resize handlers too. Use distinct names and appropriate lifetimes when several components share a window.
Removing an event handler does not cancel an already scheduled setTimeout. detach() also calls clearTimeout(timer). attach() first detaches previous registration and pending work, and Reset reuses the same cleanup. Clean up both handlers and timers when removing a component or changing pages.
In existing code, .resize(handler) registers while .resize() with no arguments notifies. This Console snippet tests the legacy shorthand on an independent object without resizing the real window or changing the main example’s counters. Use the earlier .on() and .trigger() forms for new code.
const $target = $({});
let calls = 0;
$target.resize(function () { calls++; });
$target.resize();
console.log(`legacy shorthand calls=${calls}`);
$target.off("resize");
legacy shorthand calls=1
Decide whether resize is the right tool
CSS media queries can handle simple columns, colors and borders. Check whether CSS suffices before repeatedly reading widths and writing styles in JavaScript. Here CSS controls the border, while JavaScript reports event counts and state.
Debounce processes the final size instead of every intermediate step. For work requiring continuous feedback during resizing, that deliberate delay may feel unresponsive; define the required timing first. Avoid running heavy work such as a server request for every event or continually appending identical output to the Document Object Model (DOM).
Sidebar, font or content changes can resize an element while the window stays unchanged; window resize alone cannot detect all such changes. With ResizeObserver, distinguish the measured box from the element being changed, and avoid repeatedly changing the observed size in its callback. Window dimensions in CSS pixels are also different from physical display resolution.




