I’m trying to make a webpage where a div element changes its background color as the user scrolls down the page. I want the color to transition smoothly between different shades as the scroll progresses. I’ve tried using window.onscroll, but I’m struggling to get the right values to make the color change look smooth. Could anyone show me how to achieve this effect using vanilla JavaScript? Thanks in advance!
I attempted using window.onscroll to detect the scroll position and then change the backgroundColor of the div. I tried calculating a color value based on window.scrollY but found the colors were changing too abruptly. Here’s a snippet of what I’ve got so far:
window.onscroll = () => {
const scrollPos = window.scrollY;
const colorValue = Math.min(255, scrollPos / 5); // Attempt to scale color with scroll
document.getElementById('myDiv').style.backgroundColor = `rgb(${colorValue}, 100, 150)`;
};
What I Expected:
"I was hoping for a smooth transition where the background color would gradually change as I scroll down the page. Right now, it’s either changing too quickly or jumping to values I didn’t intend. I’m also open to using different color transitions if there’s a better approach to achieve a fluid, natural effect."
4
Answers
As written, the
colorValue
will have 255 / 5 steps, no matter how may steps are in the window, so the entire color effect will occur in the first 51 lines.You might try setting the
colorValue
to a percentage of the scroll position compared to the full length and see if that’s more to your liking.This version runs on all 3 of RGB so it is extra smooth
If you use the ratio of the scrollable area to the content, you will get a smooth transition from 0 to 255.
In this snippet you can see that gradual change in the color changing and the console output of the color value.
Map the scroll position to a range of color values.