Calculating Visible Range
You'll learn how to mathematically determine which list items are currently visible in the viewport for virtual scrolling implementations.
The Core Problem
When building a virtual scroll list with thousands of items, you can't render them all—only the ones currently visible plus a small buffer. To do this, you need to calculate which items are visible based on three key pieces of information:
- Scroll position — how far down the user has scrolled
- Container height — the visible viewport height
- Item height — how tall each item is (assuming uniform height)
Think of it like looking through a narrow window at a very tall building. You can only see floors 10-15 at any moment. As you move the window up or down, you need to recalculate which floors are visible.
The Math Behind Visible Range
The formula is straightforward:
const scrollTop = container.scrollTop;
const containerHeight = container.clientHeight;
const itemHeight = 50; // pixels per item
// First visible item (rounded down)
const startIndex = Math.floor(scrollTop / itemHeight);
// Last visible item (rounded up)
const endIndex = Math.ceil((scrollTop + containerHeight) / itemHeight);
If you're scrolled 500px down and each item is 50px tall, the first visible item starts at index 10 (500 ÷ 50). If your container is 300px tall, you can fit 6 items, so the range is items 10–16.
You'll typically add a buffer (render a few extra items above and below) to create smooth scrolling without visual gaps during fast scrolling.
Key Takeaway: Calculating visible range divides scroll position by item height to find the start index, then adds container height to find the end index—this tells your virtual scroller exactly which items to render.