Here's a quick snippet from a similar feature I made where I change the opacity based on percentage scrolled of the screen.
const [percentageScrolled, setPercentageScrolled] = createSignal(0);
let handlingScroll = false;
onMount(() => {
document.addEventListener(
"scroll",
() => {
if (!handlingScroll) {
handlingScroll = true;
window.requestAnimationFrame(() => {
const p = Math.min(Math.round((window.scrollY / window.innerHeight) * 100) / 100, 1);
setPercentageScrolled(p);
handlingScroll = false;
});
}
},
{ passive: true }
);
});
You may also be interested in the Solid Primitive useWindowScrollPosition which abstracts some of these performs considerations away. Especially useful if you plan doing more with scroll positions in other components because it creates a single listener to be used in other places.
https://github.com/solidjs-community/solid-primitives/tree/main/packages/scroll#useWindowScrollPosition