Silverfang890
Silverfang890

Reputation: 1

How to animate scroll progress bar color with framer motion useScroll?

I successfully implemented a scaling scroll progress bar using framer motion, but I also want the color to change as the bar fills up. So it would start at hsl(216, 100%, 50%), empty/small bar, and end at hsl(156, 100%, 50%), full bar. Below is how I set up my motionvalues.

const { scrollYProgress } = useScroll();
const scaleX = useSpring(scrollYProgress, {
    stiffness: 200,
    damping: 50
})
const hue = useTransform(scrollYProgress, [0, 1], [216, 156])
function progressBarColor({ hue }) {
    return "hsl(" + hue + ", 100%, 50%)"
}

I have tried writing a function that returns a hsl like below, but I get a runtime error saying that "hsl(undefined, 100%, 50%) is not an animatable color".

function progressBarColor({ hue }) {
    return "hsl(" + hue + ", 100%, 50%)"
}

I understand that the 'hue' param here would be a MotionValue, so when I call the function, I call:

<motion.div id="navbar-progress" 
    animate={{
        backgroundColor: progressBarColor(hue.get())
    }}
    style={{
        scaleX: scaleX
    }}
/>

and here is my css for "navbar-progress":

#navbar-progress {
    position: absolute;
    left: 0;
    right: 0;
    height: 3px;
    background-color: #00e6ff;
    transform-origin: 50%;
}

Upvotes: 0

Views: 2039

Answers (1)

Starcc
Starcc

Reputation: 486

const { scrollYProgress } = useScroll();
const scaleX = useSpring(scrollYProgress, {
  stiffness: 200,
  damping: 50
});

const hue = useTransform(scrollYProgress, [0, 1], [216, 156]);

function progressBarColor(hueValue) {
  return `hsl(${hueValue}, 100%, 50%)`;
}

<motion.div
  id="navbar-progress"
  animate={{
    backgroundColor: progressBarColor(hue.get())
  }}
  style={{
    scaleX: scaleX
  }}
/>

Hope this one help you

Upvotes: 0

Related Questions