I have a vertical line ( not at the top of web page). This line has a circle at top, and I want it(circle) to move downward on scroll when it is in viewport, similarly upwards when I scroll upwards. I cant make this code work. Circle will stop moving after reaching top or bottom of vertical line. Can you help me to find where am I wrong?
This is what I tried:
export default function Move() {
const [scrollPosition, setScrollPosition] = useState(0);
const lineLength = 900; // Height of the vertical line
const handleScroll = ([entry]: any) => {
const currentPosition = Math.min(
Math.max(entry.intersectionRatio * lineLength, 0),
lineLength
);
setScrollPosition(currentPosition);
};
const containerRef = useRef(null);
useEffect(() => {
const options = {
root: null,
rootMargin: "0px",
threshold: [0, 0.5, 1],
};
const observer = new IntersectionObserver(handleScroll, options);
if (containerRef.current) {
observer.observe(containerRef.current);
}
return () => {
if (containerRef.current) {
observer.unobserve(containerRef.current);
}
};
}, []);
return (
<div className="flex items-center justify-center min-h-screen">
<div className="relative flex flex-col items-center">
<div
className="absolute bg-blue-500 w-5 h-5 rounded-full"
style={{ top: `${scrollPosition}px` }}
/>
<div className="h-[900px] w-0.5 bg-gray-400" />
</div>
<div ref={containerRef} style={{ height: "0", visibility: "hidden" }} />
</div>
);
}