---
title: Virtual list
description: 'A list of 10,000 lines that puts only the rows in view in the page, and that find in page still searches.'
order: 13
---

import { PrimitiveExample } from '@/components/primitive-example';
import { RecipeCode, RecipeExample, RecipePattern, RecipePatterns } from '@/components/recipe-patterns';

export const config = {
	dependencies: {
		components: [PrimitiveExample, RecipePatterns, RecipeCode, RecipeExample],
		scripts: ['./virtual-list.script.ts', './virtual-list.element.ts'],
		stylesheets: ['./virtual-list.css'],
	},
};

# Virtual list

<p class="docs-lede">
	A build log of 10,000 lines that keeps a couple of dozen rows in the page at a time, jumps to any line, and still
	answers find in page.
</p>

## Goal

A log, a long table or a feed with thousands of rows: rendering every row makes the page slow to build and to scroll, so only the rows in view are elements, and the rest are space. Rows that wrap are measured, so each sits right under the one before, and a line out of view can still be reached by its number or by the browser's find.

## Primitives

- [VirtualizerController](/docs/controllers/virtualizer) works out which rows are in view. On each scroll it reports the range to render through `onRange`, with every row's offset and the `total` height; `measure(index, element)` replaces the estimated height of a row with its real one, and `scrollToIndex` scrolls a line to the top. With `findable`, it keeps a `hidden="until-found"` stand-in holding the text of each row that is not rendered, and scrolls a row into view when find in page matches its stand-in.

Left to the recipe: rendering the rows of the range at their offsets, the spacer sized to `total`, and the ARIA. The rows in the page are not the whole list, so each row carries `aria-setsize` (the 10,000) and `aria-posinset` (its line number), and a screen reader reads "line 5,000 of 10,000" rather than the count of the rows that happen to be rendered.

## Example

Scroll the log, type a line number and press Go, or search the page for a line such as `Line 6001` with the browser's find. The caption shows how many rows are in the page. Pick an authoring pattern below; they behave the same, and the one you pick is remembered on the other recipes.

<RecipePatterns patterns={['element', 'plain']}>

<RecipePattern id="element">

The same behavior as a `RadiantElement`. The markup is authored inside the element, which finds its parts with `@query`.

```ts title="virtual-list.element.ts"
import { RadiantElement, customElement, onEvent, query } from '@ecopages/radiant';
import { createVirtualizerController, type VirtualRange } from '@ecopages/radiant-ui/controllers';
import { LINE_COUNT, LINE_ESTIMATE, lineText } from './virtual-list.data';

@customElement('virtual-list-element')
export class VirtualListElement extends RadiantElement {
	@query('[data-scroller]') private scroller!: HTMLElement;
	@query('[data-spacer]') private spacer!: HTMLElement;
	@query('[data-spacer] ul') private list!: HTMLUListElement;
	@query('[data-findable]') private findableLayer!: HTMLElement;
	@query('input') private input!: HTMLInputElement;
	@query('[data-status]') private status!: HTMLElement;

	private readonly virtualizer = createVirtualizerController(this, {
		getScroller: () => this.scroller,
		getCount: () => LINE_COUNT,
		estimate: () => LINE_ESTIMATE,
		onRange: (range) => this.showRange(range),
		findable: { text: lineText, getLayer: () => this.findableLayer },
	});

	@onEvent({ selector: 'form', type: 'submit' })
	goToLine(event: SubmitEvent): void {
		event.preventDefault();
		this.virtualizer.scrollToIndex(this.input.valueAsNumber - 1, { align: 'start' });
	}

	private showRange({ items, total }: VirtualRange): void {
		this.spacer.style.height = `${total}px`;
		const rows = items.map(({ index, start }) => {
			const row = document.createElement('li');
			row.textContent = lineText(index);
			row.setAttribute('aria-setsize', String(LINE_COUNT));
			row.setAttribute('aria-posinset', String(index + 1));
			row.style.transform = `translateY(${start}px)`;
			return row;
		});
		this.list.replaceChildren(...rows);
		rows.forEach((row, position) => this.virtualizer.measure(items[position]!.index, row));
		this.status.textContent = `${rows.length} of ${LINE_COUNT.toLocaleString('en')} lines in the page`;
	}
}
```

```ts title="virtual-list.data.ts"
/** How many lines the log has. */
export const LINE_COUNT = 10_000;

/** The height in px of a one-line row, which the virtualizer assumes until a row is measured. */
export const LINE_ESTIMATE = 32;

const STEPS = [
	'resolved dependencies',
	'compiled 48 modules',
	'type-checked the workspace',
	'bundled the client entry',
	'ran 1,204 tests, all passing, across the controllers, helpers and components suites in Chromium, Firefox and WebKit',
	'wrote the server bundle',
	'copied static assets',
];

/** The text of line `index`. One line in seven is long enough to wrap, so the rows differ in height. */
export function lineText(index: number): string {
	return `Line ${index + 1}: ${STEPS[index % STEPS.length]}`;
}
```

```html title="virtual-list.html"
<virtual-list-element>
	<div data-scroller role="region" aria-label="Build log" tabindex="0">
		<div data-spacer>
			<ul></ul>
			<div data-findable aria-hidden="true"></div>
		</div>
	</div>
	<form>
		<label for="virtual-line">Go to line</label>
		<input id="virtual-line" name="line" type="number" min="1" max="10000" value="5000" required />
		<button type="submit">Go</button>
	</form>
	<p data-status></p>
</virtual-list-element>
```

```css title="virtual-list.css"
:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) {
	display: flex;
	flex-direction: column;
	align-items: stretch;
	gap: var(--space-stack);
	box-sizing: border-box;
	width: min(100%, 30rem);
	padding: var(--space-inset);
	border: 1px solid var(--border);
	border-radius: var(--radius-container);
	background: var(--surface);
	color: var(--on-surface);
	box-shadow: var(--shadow-overlay);
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) [data-scroller] {
	flex: none;
	box-sizing: border-box;
	height: 18rem;
	overflow-y: auto;
	padding: 0;
	overscroll-behavior: contain;
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--surface-container-low);
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) [data-scroller]:focus-visible {
	outline: 2px solid var(--focus-ring);
	outline-offset: 1px;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) [data-spacer] {
	position: relative;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) :is(ul, [data-findable]) {
	position: absolute;
	inset: 0;
	margin: 0;
	padding: 0;
	border: 0;
	background: transparent;
	list-style: none;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example))
	[data-findable]
	> [hidden='until-found'] {
	display: block;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) li {
	position: absolute;
	inset-block-start: 0;
	inset-inline: 0;
	box-sizing: border-box;
	padding: 0.375rem 0.75rem;
	border: 0;
	border-block-end: 1px solid var(--border);
	border-radius: 0;
	background: transparent;
	font-family: var(--font-mono, monospace);
	font-size: 0.8125rem;
	line-height: 1.25rem;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) form {
	display: grid;
	grid-template-columns: minmax(0, 1fr) auto;
	column-gap: var(--space-stack);
	row-gap: 0.375rem;
	align-items: end;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) :where(label) {
	grid-column: 1 / -1;
	font-size: 0.75rem;
	font-weight: 600;
	letter-spacing: 0.04em;
	text-transform: uppercase;
	opacity: 0.7;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) input {
	box-sizing: border-box;
	width: 100%;
	min-height: var(--size-control-lg);
	padding: var(--space-control-y) var(--space-control-x);
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--surface-container-low);
	color: inherit;
	font: inherit;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) button {
	min-height: var(--size-control-lg);
	padding: var(--space-control-y) var(--space-control-x);
	border: 1px solid transparent;
	border-radius: var(--radius-control);
	background: var(--primary);
	color: var(--on-primary);
	font: inherit;
	font-weight: 600;
	cursor: pointer;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example))
	:where(input, button):focus-visible {
	outline: 2px solid var(--focus-ring);
	outline-offset: 1px;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) [data-status] {
	margin: 0;
	font-size: 0.75rem;
	font-variant-numeric: tabular-nums;
	opacity: 0.65;
}
```

`createVirtualizerController(this, ...)` attaches when the element connects, which reports the first range and adds the stand-ins, and destroys the controller when the element disconnects, which removes them. The method that draws the range is not called `render`, because a `RadiantElement` keeps that name for the markup it draws itself.

What the Radiant form removes: the `mount` function and its registration, the listener to remove, and the cleanup to return and call.

</RecipePattern>

<RecipePattern id="plain">

A `mount` function wires the controller to one element and returns the cleanup that undoes it.

```ts title="virtual-list.script.ts"
import { VirtualizerController, type VirtualRange } from '@ecopages/radiant-ui/controllers';
import { LINE_COUNT, LINE_ESTIMATE, lineText } from './virtual-list.data';

export function mount(root: HTMLElement): () => void {
	const scroller = root.querySelector<HTMLElement>('[data-scroller]')!;
	const spacer = root.querySelector<HTMLElement>('[data-spacer]')!;
	const list = spacer.querySelector('ul')!;
	const form = root.querySelector('form')!;
	const input = form.querySelector('input')!;
	const status = root.querySelector('[data-status]')!;

	const render = ({ items, total }: VirtualRange) => {
		spacer.style.height = `${total}px`;
		const rows = items.map(({ index, start }) => {
			const row = document.createElement('li');
			row.textContent = lineText(index);
			row.setAttribute('aria-setsize', String(LINE_COUNT));
			row.setAttribute('aria-posinset', String(index + 1));
			row.style.transform = `translateY(${start}px)`;
			return row;
		});
		list.replaceChildren(...rows);
		rows.forEach((row, position) => virtualizer.measure(items[position]!.index, row));
		status.textContent = `${rows.length} of ${LINE_COUNT.toLocaleString('en')} lines in the page`;
	};

	const virtualizer = new VirtualizerController({
		getScroller: () => scroller,
		getCount: () => LINE_COUNT,
		estimate: () => LINE_ESTIMATE,
		onRange: render,
		findable: { text: lineText, getLayer: () => root.querySelector<HTMLElement>('[data-findable]')! },
	});
	virtualizer.attach();

	const goToLine = (event: SubmitEvent) => {
		event.preventDefault();
		virtualizer.scrollToIndex(input.valueAsNumber - 1, { align: 'start' });
	};
	form.addEventListener('submit', goToLine);

	return () => {
		form.removeEventListener('submit', goToLine);
		virtualizer.destroy();
	};
}
```

```ts title="virtual-list.data.ts"
/** How many lines the log has. */
export const LINE_COUNT = 10_000;

/** The height in px of a one-line row, which the virtualizer assumes until a row is measured. */
export const LINE_ESTIMATE = 32;

const STEPS = [
	'resolved dependencies',
	'compiled 48 modules',
	'type-checked the workspace',
	'bundled the client entry',
	'ran 1,204 tests, all passing, across the controllers, helpers and components suites in Chromium, Firefox and WebKit',
	'wrote the server bundle',
	'copied static assets',
];

/** The text of line `index`. One line in seven is long enough to wrap, so the rows differ in height. */
export function lineText(index: number): string {
	return `Line ${index + 1}: ${STEPS[index % STEPS.length]}`;
}
```

```html title="virtual-list.html"
<div data-example="virtual-list">
	<div data-scroller role="region" aria-label="Build log" tabindex="0">
		<div data-spacer>
			<ul></ul>
			<div data-findable aria-hidden="true"></div>
		</div>
	</div>
	<form>
		<label for="virtual-line">Go to line</label>
		<input id="virtual-line" name="line" type="number" min="1" max="10000" value="5000" required />
		<button type="submit">Go</button>
	</form>
	<p data-status></p>
</div>
```

```css title="virtual-list.css"
:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) {
	display: flex;
	flex-direction: column;
	align-items: stretch;
	gap: var(--space-stack);
	box-sizing: border-box;
	width: min(100%, 30rem);
	padding: var(--space-inset);
	border: 1px solid var(--border);
	border-radius: var(--radius-container);
	background: var(--surface);
	color: var(--on-surface);
	box-shadow: var(--shadow-overlay);
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) [data-scroller] {
	flex: none;
	box-sizing: border-box;
	height: 18rem;
	overflow-y: auto;
	padding: 0;
	overscroll-behavior: contain;
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--surface-container-low);
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) [data-scroller]:focus-visible {
	outline: 2px solid var(--focus-ring);
	outline-offset: 1px;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) [data-spacer] {
	position: relative;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) :is(ul, [data-findable]) {
	position: absolute;
	inset: 0;
	margin: 0;
	padding: 0;
	border: 0;
	background: transparent;
	list-style: none;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example))
	[data-findable]
	> [hidden='until-found'] {
	display: block;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) li {
	position: absolute;
	inset-block-start: 0;
	inset-inline: 0;
	box-sizing: border-box;
	padding: 0.375rem 0.75rem;
	border: 0;
	border-block-end: 1px solid var(--border);
	border-radius: 0;
	background: transparent;
	font-family: var(--font-mono, monospace);
	font-size: 0.8125rem;
	line-height: 1.25rem;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) form {
	display: grid;
	grid-template-columns: minmax(0, 1fr) auto;
	column-gap: var(--space-stack);
	row-gap: 0.375rem;
	align-items: end;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) :where(label) {
	grid-column: 1 / -1;
	font-size: 0.75rem;
	font-weight: 600;
	letter-spacing: 0.04em;
	text-transform: uppercase;
	opacity: 0.7;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) input {
	box-sizing: border-box;
	width: 100%;
	min-height: var(--size-control-lg);
	padding: var(--space-control-y) var(--space-control-x);
	border: 1px solid var(--border);
	border-radius: var(--radius-control);
	background: var(--surface-container-low);
	color: inherit;
	font: inherit;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) button {
	min-height: var(--size-control-lg);
	padding: var(--space-control-y) var(--space-control-x);
	border: 1px solid transparent;
	border-radius: var(--radius-control);
	background: var(--primary);
	color: var(--on-primary);
	font: inherit;
	font-weight: 600;
	cursor: pointer;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example))
	:where(input, button):focus-visible {
	outline: 2px solid var(--focus-ring);
	outline-offset: 1px;
}

:is(virtual-list-element, div[data-example='virtual-list']:not(.primitive-example)) [data-status] {
	margin: 0;
	font-size: 0.75rem;
	font-variant-numeric: tabular-nums;
	opacity: 0.65;
}
```

`mount` runs once for each example element on the page, and the function it returns undoes it; see [how the examples run](/docs/recipes/overview#how-the-examples-run).

</RecipePattern>

</RecipePatterns>

### Styles

The stylesheet is the `virtual-list.css` tab in the files above. The scroller has a fixed height, the spacer inside it is `position: relative` and gets its height from `total`, and each row is absolutely positioned and moved to its offset with `transform`, so a new range moves no other row. The stand-in layer is an absolutely positioned sibling of the list, at the same origin, so a stand-in the browser reveals sits where its row will be. The selectors are scoped to the example on this site; drop the scope in your own project.

## Accessibility

- Each row carries `aria-setsize` and `aria-posinset`, so a screen reader announces its place in the whole list, not among the rendered rows.
- The scroller has `role="region"`, a name and `tabindex="0"`, so the keyboard can reach it and scroll it; nothing inside it is focusable.
- The stand-in layer has `aria-hidden="true"`. A stand-in that find in page reveals shows until the next frame, and a screen reader should not read it beside its row.
- The controller writes no ARIA; the recipe sets all of the above.

## What to watch for

- **Measure every rendered row, on every range.** A row of the estimated height needs no measuring, but a row that wraps does, and only measuring tells which. When the scroller changes width the controller reports the range again, so the rows are drawn and measured again at their new heights.
- **Rows render from the range, not from the DOM.** Replacing the rows on each range is the simplest correct render. A recipe that keeps row elements and reuses them for other lines must measure each one again for its new line.
- **Keep the stand-ins displayed.** A rule such as `[hidden] { display: none }` that reaches a stand-in hides it from find in page, so the stylesheet gives `[hidden='until-found']` in the layer `display: block`; the docs frame around this example has such a rule.
- **Find in page costs one element per line.** The stand-ins are cheap, since a hidden element is not laid out, but they are elements: fine for thousands of lines, not for millions. Leave `findable` out where the browser's find does not matter.
- **Offsets start at the scroller's edge.** Put nothing before the spacer inside the scroller, and give the scroller no padding along the axis, or the offsets the controller reports are off by that much.
