Branchwell

Become a Pro / website · becomeapro.ai / src / components / reveal-on-scroll.tsx

Raw 990 B on 5069836c1e4c4e369ebe86b13dc7d299c5bed8c0
1"use client";
2
3import { useEffect } from "react";
4
5// Fades blocks in as they scroll into view. Only blocks that start below the fold are hidden, so nothing on the
6// first screen flickers, and without JavaScript everything simply shows.
7export function RevealOnScroll({ selector }: { selector: string }) {
8 useEffect(() => {
9 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
10 const els = Array.from(document.querySelectorAll<HTMLElement>(selector)).filter(
11 (el) => el.getBoundingClientRect().top > window.innerHeight
12 );
13 const io = new IntersectionObserver(
14 (entries) =>
15 entries.forEach((e) => {
16 if (!e.isIntersecting) return;
17 e.target.classList.add("in");
18 io.unobserve(e.target);
19 }),
20 { rootMargin: "0px 0px -8% 0px" }
21 );
22 els.forEach((el) => {
23 el.classList.add("reveal");
24 io.observe(el);
25 });
26 return () => io.disconnect();
27 }, [selector]);
28 return null;
29}