I have a css variable named --color. I want to change the value of this css variable as the page scrolls down. The scrolling of the page should "scrub" the value.
Example: --color starts out at rgb(255, 255, 255). As the page scrolls down, the value gets closer to and eventually reaches rgb(0, 0, 0) upon scrolling down all the way. When scrolling back up, the value should slowly advance back to rgb(255, 255, 255), reaching it by the time the page is scrolled up completely.
I have been trying to achieve this with GSAP but have yet to find any success, although I believe it must be possible with the library.
Sure, here you go:
gsap.to("body", {
"--color": "black",
scrollTrigger: {
start: 0,
end: "max",
scrub: true
}
});
https://codepen.io/GreenSock/pen/WNOzWaM?editors=0110
By the way, there are dedicated GSAP forums at https://greensock.com/forums
unfortunately I am not familiar with GSAP, but here is the link that describes how to get the computed styles and the property value of that style with JS. You need to listen to scroll event and change the value of the css variable inside of the listener, like so:
document.addEventListener('scroll', function(e) {
var root = document.querySelector(':root');
var newColor = // do your color calculations here;
root.style.setProperty('--color', newColor);
}
here are some useful links.
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/getPropertyValue https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
It's helpful when you provide a code snippet to show what has already been attempted. Helps with specificity of the answer.
To give a general answer to your question, you can use ScrollTrigger to define the point at which the color changes. Define the markers where it should start changing and use properties such as coloronEnter, onLeave, onEnterBack to your callback to change the color.