2

I am using react spring to animate the window scroll 500 ms after the component is mounted. The problem happens if the scroll animation and the user's scroll happen at the same time. I made it check if the page scroll is 0 before it starts animating but that only solves if the user scrolls before the 500ms trigger.

Here is the code:

const [, setY] = useSpring(() => ({ y: window.innerHeight * 0.05 }))

useEffect(() => {
    setTimeout(() => {
        // Cross browser way of knowing how much the user has scrolled the page.
        const scrollTop = (window.pageYOffset !== undefined)
            ? window.pageYOffset
            : (document.documentElement || document.body.parentNode || document.body).scrollTop
        // Checks if the user hasn't scrolled himself.
        if (scrollTop === 0) {
            // Animates.
            setY({
                y: window.innerHeight * 0.05,
                reset: true,
                from: { y: window.scrollY },
                onFrame: props => window.scroll(0, props.y)
            })
        }
    }, 500)
}, [])

I also tried destructuring the stop function to and using it inside onFrame but it doesn't seem to work:

const [, setY, stop] = useSpring(() => ({ y: window.innerHeight * 0.05 }))

Also window.scroll() triggers the scroll event so I can't distinguish scripted scroll from user scroll.

Any ideas on how I can solve this problem?

Thanks in advance!

Mohamed Seif Khalid
  • 555
  • 1
  • 4
  • 14

1 Answers1

0

I used this: let user scrolling stop jquery animation of scrolltop?

I made my own react based event handler

  const cancelEvents = [
    "scroll",
    "mousedown",
    "DOMMouseScroll",
    "mousewheel",
    "keyup",
    "touchstart",
    "touchmove",
  ];

  const cancelAnimationHandler = useCallback((e) => {
    if (
      e.which > 0 ||
      cancelEvents.reduce(
        (accumulator, currentValue) =>
          e.type === accumulator || e.type === currentValue
      )
    ) {
      api.stop();
    }
  }, []);
  useEffect(() => {
    cancelEvents.map((event) =>
      window.addEventListener(event, cancelAnimationHandler)
    );
    () =>
      cancelEvents.map((event) =>
        window.removeEventListener(event, cancelAnimationHandler)
      );
  }, [cancelAnimationHandler]);