preventScroll Keeps Focus Without Scrolling

Call focus({ preventScroll: true }) for keyboard navigation so focus moves between panes without scrolling the viewport away from the reader.

TypescriptData Integrity

Code

typescriptsnippet
17 lines
// focus() scrolls the newly focused control into view by default, which
// yanks a two-pane layout when the list lives in a side pane. The
// preventScroll option moves focus without touching scroll positions.
const rows = Array.from(document.querySelectorAll<HTMLElement>('.cmd-row'));

document.addEventListener('keydown', (event: KeyboardEvent) => {
  if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
  event.preventDefault();

  const index = rows.indexOf(document.activeElement as HTMLElement);
  const step = event.key === 'ArrowDown' ? 1 : -1;
  const next = rows[(index + step + rows.length) % rows.length];
  if (!next) return;

  next.focus({ preventScroll: true });
  console.log('focused row:', next.dataset['cmd']);
});

How the code works

Top-level bindings rows hold the demo state — nothing sits inside a function scope.

Watch out for

  • Every symbol it touches is built into the language — nothing needs fetching.
  • document exist only in browsers — a Node runtime has no shims for them out of the box.
  • The guard event.key !== 'ArrowDown' && event.key !== 'ArrowUp' exits the flow early through return when its condition holds.

Applying it

The run emits 1 labeled section — focused row: — one per step.

Statements that matter

const rows = Array.from(document.querySelectorAll<HTMLElement>('.cmd-row'));

Interactive Tools for This Topic

FAQ

Does preventScroll Keeps Focus Without Scrolling run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.