Emmanuel Akinfulubi

JavaScriptDOM

Display the window size on resize in JavaScript

Intermediate · 4 min read

Some pages need to know how big the browser window is right now: a chart that redraws to fit, a menu that switches to a phone layout, a game that scales its board. The window can change size at any moment, so the page has to keep listening.

In this tutorial you will show the window's width and height on the page and keep them up to date as the window is resized. Then you will meet a technique called debouncing, which stops slow work from running dozens of times a second. You should know what a function is and have used addEventListener.

Reading the window size

The browser's window object has two numbers for this:

  • window.innerWidth is the width of the visible area, in pixels.
  • window.innerHeight is its height.

Both include the scrollbar, if there is one. document.documentElement.clientWidth gives the width without the scrollbar, which is the space your page's content actually has.

The resize event

Whenever the window changes size, window fires a resize event. While someone drags the edge of the window, it doesn't fire once at the end. It fires again and again throughout the drag.

Here is the exercise. Try it yourself first, or read on and we will build it.

13 Report the window size as it changes

fair

Show the window's width and height, and keep it up to date as the window is resized.

Stuck? Three hints, smallest first
  1. 1. window.innerWidth and innerHeight include the scrollbar; documentElement.clientWidth does not.
  2. 2. Resize fires continuously while dragging, so do not do real work on every event.
  3. 3. Report the size once at the start too, or the display is empty until the first resize.

Step 1: show the size once

The page has one element for the output:

index.html

<pre id="out"></pre>

A pre element keeps line breaks, so \n in the text starts a new line.

Step 1

const out = document.getElementById('out');
const size = () => ({ width: window.innerWidth, height: window.innerHeight });
function report() {
  const { width, height } = size();
  out.textContent = `width ${width}\nheight ${height}`;
}
report();

size returns both numbers in one object, and report writes them on the page. const { width, height } = size() takes the two properties out of the object into two variables with the same names.

Calling report() once straight away matters. Without it, the box stays empty until the first resize, which might never happen.

Step 2: update it on every resize

Step 2

const out = document.getElementById('out');
function report() {
  out.textContent = `width ${window.innerWidth}\nheight ${window.innerHeight}`;
}
window.addEventListener('resize', report);
report();

That is the whole basic exercise. Drag the edge of the live demo's frame and the numbers follow.

Step 3: why some work shouldn't run on every event

Writing two numbers is cheap. But suppose that, on resize, you also redraw a big chart. One drag can fire dozens of resize events, and redrawing for every one of them makes the page stutter. You only really want to redraw once, when the person stops dragging.

Step 4: debounce the slow part

Debouncing means "wait until things go quiet, then act once". On each event you cancel the timer from the last event and start a new one. Only the last timer survives long enough to run.

Here is the idea in plain JavaScript, so you can run it with no window at all. onResize stands in for the event listener, and four quick calls stand in for a drag:

Step 4

let rawEvents = 0;
let workDone = 0;
let timer = null;
function onResize() {
  rawEvents++;                               // the cheap part runs every time
  clearTimeout(timer);                       // cancel the last timer
  timer = setTimeout(() => {                 // start a new one
    workDone++;                              // the slow part
    console.log('events', rawEvents, 'work', workDone); // events 4 work 1
  }, 150);
}
onResize();
onResize();
onResize();
onResize();

Four events, but the slow part ran once, 150 milliseconds after the last one. Each call to clearTimeout(timer) throws away the previous timer before it gets a chance to run.

In the page, the listener does both: the cheap update every time, the slow work debounced.

JavaScript

let timer = null;
window.addEventListener('resize', () => {
  report();                                  // cheap: always fine
  clearTimeout(timer);
  timer = setTimeout(() => {
    // expensive work goes here, for example redrawing a chart
  }, 150);
});
report();

The live demo counts both numbers as you resize: the raw events climb fast, and the "work done" count goes up once each time you stop.

The full solution

The full solution can't resize a real window, so it uses a small stand-in where window.resizeTo(w, h) sets the size and fires resize, and a fake clock that the test moves forward by hand. Its checks confirm the size shows before any resize, four quick resizes fire four events but run the slow work once, and the display ends on the last size. Press Run to see it.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

// ---- the stand-in ----------------------------------------------------------
// A debounce needs a timer the test can drive, so the clock is injected. The
// window stand-in has resizeTo(w, h), which sets the size and fires 'resize' —
// a real window has no such method; it is how a test resizes without a browser.
function makeClock() {
  let now = 0;
  let jobs = [];
  let nextId = 1;
  return {
    setTimeout(fn, ms) { const id = nextId++; jobs.push({ id, fn, at: now + ms }); return id; },
    clearTimeout(id) { jobs = jobs.filter((j) => j.id !== id); },
    advance(ms) {
      now += ms;
      const due = jobs.filter((j) => j.at <= now).sort((a, b) => a.at - b.at);
      jobs = jobs.filter((j) => j.at > now);
      for (const job of due) job.fn();
    },
  };
}

// ---- the answer ------------------------------------------------------------
const out = el('pre', { id: 'out' });
document.body.appendChild(out);

const clock = makeClock();
let rawEvents = 0;
let workDone = 0;

const size = () => ({ width: window.innerWidth, height: window.innerHeight });

function report() {
  const { width, height } = size();
  out.textContent = `width ${width}\nheight ${height}`;
}

let timer = null;
window.addEventListener('resize', () => {
  rawEvents++;
  report();                                  // cheap: always fine
  clock.clearTimeout(timer);
  timer = clock.setTimeout(() => { workDone++; }, 150);   // expensive: debounced
});

report();          // once up front, so it is never blank

// Snapshotted NOW. Asserting against out.textContent later would read the value
// after the resizes below, which is a different claim.
const atRest = out.textContent;

console.log('at rest        :', atRest.replace('\n', ', '));

// A drag fires many events in quick succession.
for (const [w, h] of [[1000, 700], [900, 650], [800, 600], [760, 580]]) {
  window.resizeTo(w, h);
  clock.advance(20);                          // still mid-drag
}
console.log('during a drag  : events', rawEvents, 'work', workDone);
clock.advance(200);                           // the drag stopped
console.log('after it settles: events', rawEvents, 'work', workDone);
console.log('final size     :', out.textContent.replace('\n', ', '));

Output


      
13 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 13 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

13 checks

test('the size is reported before any resize', atRest.startsWith('width 1024'), true);
test('the initial height too', atRest.includes('height 768'), true);
test('four resize events fired', rawEvents, 4);
test('but the expensive work ran once', workDone, 1);
test('so the debounce collapsed four into one', rawEvents > workDone, true);
test('the display shows the final width', out.textContent.includes('width 760'), true);
test('and the final height', out.textContent.includes('height 580'), true);
test('window.innerWidth agrees', window.innerWidth, 760);
test('and innerHeight', window.innerHeight, 580);
test('a further resize is reported immediately', (() => { window.resizeTo(500, 400); return size(); })(), { width: 500, height: 400 });
test('and adds one more raw event', rawEvents, 5);
test('with no extra work until the timer fires', workDone, 1);
test('then exactly one more', (() => { clock.advance(200); return workDone; })(), 2);

Adapted. There is no real window, so window here is the stand-in and resizeTo(w, h) sets the size and fires resize. The timer is injected for the same reason as the debounce exercise in the Basic section: a test cannot wait 150ms and still be a test. The live demo is a real frame — drag its edge, or resize the browser, and both counters move.

The point of the exercise is the debounce. resize fires continuously while a window is being dragged, so doing anything costly per event means dozens of layout recalculations a second. The pattern is to split the work: cheap updates run on every event, and the expensive part is delayed with a timer that gets cancelled and restarted each time, so it runs once after the movement stops. The assertions show four events producing one unit of work.

On the measurements themselves: window.innerWidth includes the scrollbar, document.documentElement.clientWidth does not. If a value is being compared against a CSS media query, use clientWidth — media queries do not count the scrollbar either, and the mismatch is a classic source of an off-by-15-pixels bug.

Common mistakes

  • Not reporting at the start. The display is empty until the first resize. Call report() once yourself.
  • Doing slow work on every resize. The event fires many times a second during a drag. Debounce anything expensive.
  • Forgetting the scrollbar. innerWidth counts it. When you need the space the content really has, use document.documentElement.clientWidth.

Try it yourself

  1. Show "phone", "tablet" or "desktop" under the numbers, based on the width (pick your own cut-off points).
  2. Change the debounce delay to 1000 milliseconds and see how long the "work done" count takes to catch up.
  3. Show document.documentElement.clientWidth next to innerWidth. On a page that scrolls, how far apart are they?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.