Become a Pro / website · becomeapro.ai / src / components / reveal-on-scroll.tsx
| 1 | "use client"; |
| 2 | |
| 3 | import { 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. |
| 7 | export 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 | } |