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.”