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.
Code
// 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.
documentexist 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 throughreturnwhen 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.