how to change background color on scroll
const [red, green, blue] = [69, 111, 225] const section1 = document.querySelector('.section1') window.addEventListener('scroll', () => { let y = 1 + (window.scrollY || window.pageYOffset) / 150 y = y < 1 ? 1 : y // ensure y is always >= 1 (due to Safari's elastic scroll) const [r, g, b] = [red/y, green/y, blue/y].map(Math.round) section1.style.backgroundColor = `rgb(${r}, ${g}, ${b})` })
Here is what the above code is Doing:
1. We’re grabbing the section1 element and storing it in a variable.
2. We’re adding an event listener to the window object that listens for the scroll event.
3. When the scroll event is fired, we’re calculating the y value.
4. We’re then using the y value to calculate the new RGB values.
5. Finally, we’re setting the background color of the section1 element to the new RGB values.