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!