im just trying to get some text to fade in and out based on the scroll position
i am using framer motion
here is my code:
const ref = useRef(null)
const { scrollYProgress } = useScroll({
target: ref,
offset: ["start end", "end end"],
})
const opacity = useTransform(
scrollYProgress,
[0, 0.5, 1],
[0, 1, 0],
)
// ...
<div ref={ref} className="flex flex-col items-center justify-center border border-blue-600 text-7xl h-screen">
<motion.div
style={{
opacity: opacity,
}}
>
hello
</motion.div>
</div>
i want it so when the scroll position is centered on the div (scrollYProgress == 0.5) then the opacity is 100%, and scrolling up or down from that point fades it out progressively based on scrollYProgress
the text is only fading out when scrolling top to bottom, not fading in & out as desired
Change your offset to ["start center", "end center"]
.
From Framer Motion's docs:
offset
is an array of at least two intersections. An intersection describes a point when thetarget
andcontainer
meet. So for example,"start end"
means when the start of the target meets the end of the container.
In your case, the target
is the div you gave the ref to. The container
is the viewport. By setting your offset to ["start end", "end end"]
, you are telling Framer Motion that the scrollYProgress should be 0 when the start of the div is at the end of the viewport and 1 when the end of the div is at the end of the viewport. This can be a bit tricky to work out without a visualization. I made this example to help see what "start", "center", and "end" mean when it comes to the offsets.
Setting your offset to ["start center", "end start"]
may also be a result you are looking for. The beauty of Framer Motion is that you can play around and accomplish these fine tuned animations.