How to detect certain scroll position with framer-motion?

6k Views Asked by At

When scrollTop is equal to 500px, I want to trigger an animation on a div with position fixed. Is there a way to do this in framer-motion. I only find solution that propose when element is in viewport. But my div is always in the viewport, because it has a fixed position. I need a build in scroll position watcher.

sandbox

import { useInView } from "react-intersection-observer";
import { motion, useAnimation } from "framer-motion";
3

There are 3 best solutions below

0
On BEST ANSWER

this is kind of old already but here is the answer.

import { useViewportScroll } from "framer-motion";

const Nav = () => {
    const { scrollY } = useViewportScroll();
    
    scrolly.onChange(y => {
    // y = scroll position
    //Do Something
    })
}

0
On

For those who are interested in latest version.

import { useScroll } from "framer-motion"

const { scrollY } = useScroll()

useMotionValueEvent(scrollY, "change", (latest) => {
  console.log("Page scroll: ", latest)
})
2
On
  const { scrollY } = useViewportScroll();

  scrollY.onChange(y => {
    console.log('y ', y)
  })

just a slight typo :)