visualViewport Tracks The Keyboard Overlap

Track the visual viewport during keyboard overlap with resize and scroll listeners, and keep the focused input inside the visible surface.

TypescriptForm Validation

Code

typescriptsnippet
21 lines
// visualViewport reports the *visible* part of the page: when the
// on-screen keyboard slides over a form, its height shrinks and the
// offset changes — the fixed layout viewport does not move
const viewport = window.visualViewport;

if (viewport) {
  const report = (): void => {
    console.log(`visible ${viewport.width}x${viewport.height}`);
  };
  viewport.addEventListener('resize', report);
  viewport.addEventListener('scroll', report);
  report();
}

// Keep the focused input in sight when the keyboard covers it
const field = document.querySelector<HTMLInputElement>('#reply');
if (field && viewport) {
  field.addEventListener('focus', () => {
    field.scrollIntoView({ block: 'nearest' });
  });
}

The viewport that actually shrinks

window.visualViewport reports the visible part of the page: when the on-screen keyboard slides over a form, its height shrinks and its offset changes while the fixed layout viewport stays put. The file guards it once — if (viewport) { ... } — then wires a local report closure to both resize and scroll events and calls it immediately, so every viewport change logs `visible ${viewport.width}x${viewport.height}`.

Keeping the focused input in sight

The second block guards field and viewport together and registers a focus listener that runs field.scrollIntoView({ block: 'nearest' }) — the minimal scroll that pulls #reply back inside the newly shrunken visible surface. block: 'nearest' avoids the jump-to-center behavior a bare scrollIntoView() would produce.

The lines that react to the keyboard

viewport.addEventListener('resize', report);
viewport.addEventListener('scroll', report);

The code needs a browser page (window, document do not exist under plain Node); both events are the browser’s own signal that the keyboard overlap changed the geometry the handlers read.

Interactive Tools for This Topic

FAQ

Does visualViewport Tracks The Keyboard Overlap run in plain Node.js?
No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.