Skip to content

Instantly share code, notes, and snippets.

@adamkleingit
Last active October 19, 2023 07:47
Show Gist options
  • Save adamkleingit/b40c0d3e3b530b2d7160dd0b5dc270f2 to your computer and use it in GitHub Desktop.
Save adamkleingit/b40c0d3e3b530b2d7160dd0b5dc270f2 to your computer and use it in GitHub Desktop.
Vanilla Virtual Scroll Pseudo Code
const VirtualScroll = ({
renderItem,
itemCount,
viewportHeight,
rowHeight,
nodePadding,
}) => {
const totalContentHeight = itemCount * rowHeight;
let startNode = Math.floor(scrollTop / rowHeight) - nodePadding;
startNode = Math.max(0, startNode);
let visibleNodesCount = Math.ceil(viewportHeight / rowHeight) + 2 * nodePadding;
visibleNodesCount = Math.min(itemCount - startNode, visibleNodesCount);
const offsetY = startNode * rowHeight;
const visibleChildren = new Array(visibleNodeCount)
.fill(null)
.map((_, index) => renderItem(index + startNode));
return `
<div ${/* viewport */}
style="
height: ${viewportHeight};
overflow: "auto";
"
>
<div ${/* content */}
style="
height: ${totalContentHeight};
overflow: "hidden";
"
>
<div ${/* offset for visible nodes */}
style="
transform: translateY(${offsetY}px);
"
>
${visibleChildren} ${/* actual nodes */}
</div>
</div>
</div>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment