Motion: [FEATURE] Imperatively animate scroll position

Created on 30 Aug 2019  路  3Comments  路  Source: framer/motion

Is your feature request related to a problem? Please describe.

I'm trying to use Framer Motion to scroll a DOM element with spring physics.

Describe the solution you'd like

I guess it should be possible somehow with MotionValue, but I wasn't sure how to trigger a spring animation.

This is the code I've tried:

const scrollMotionValue = new MotionValue(scrollParent.scrollTop);
scrollMotionValue.onChange(value => {
  scrollParent.scrollTop = value;
});
scrollMotionValue.set(target);

This sets the value directly and it doesn't animate. I guess you'd have to use attach somehow? I couldn't quite figure it out.

Describe alternatives you've considered

I was able to get it to work with popmotion like this:

spring({
  from: scrollParent.scrollTop,
  to: target,
  mass: 1,
  stiffness: 400,
  damping: 40
}).start({
  update(value) {
    scrollParent.scrollTop = value;
  }
});

I haven't used popmotion before and I'm not sure if that is entirely correct.

Thanks for your help!

feature

All 3 comments

I believe you need to wrap it in a spring, in react-land like so:

const motion = useMotionValue(scrollParent.scrollTop);
const spring = useSpring(motion)

useEffect(() => {
  spring.onChange(value => scrollParent.scrollTop = value)
  motion.set(target)
}, [])

Hey @natew! Thanks, that seems to work. motion.set now animates using the spring.

However I also need a way to immediately set the motion value to a new value. The use case is that I always want to start from the current scroll position. I mean I could add a scroll event listener, which syncs the value back into the motion value, but then you'd end up in a strange chain between the scroll position and the motion value which syncs back and forth.

I couldn't find a function which does that. Calling motion.stop() before motion.set() doesn't seem to make a difference.

I'm facing a similar problem. What would be ideal is an API similar to React Native's Animated API (if you're familiar) that lets devs set the motion value value either instantly or through an animation. Ideally, there would be an additional method expose on a MotionValue to trigger an animated transition to the new value like so:

scrollMotionValue.setWithAnimation(100, { someConfig: true })
Was this page helpful?
0 / 5 - 0 ratings