There are various ways to make a webpage change color as the user scrolls down. One way is to use JavaScript to add an event listener to the window
object for the scroll
event
Below is an example of a sample webpage that uses the above technique. Please scroll through the webpage to see the effect.
Let's look at how we can get this effect:
In the Javascript file above, we've highlighted the chunk of the code responsible for the background color change.
We've added an event listener that listens to the scroll
event and calculates the position of the scroll when the user scrolls. Based on the scroll positions, it then calculates the different background colors by multiplying the initial RGB values with the current scroll position.
window.addEventListener('scroll', () => {/* calculating the vertical scroll position of the page usingthe `window.scrollY` property */const topScroll = window.scrollY;/* calculating the maximum scroll height of the page by subtractingthe height of the viewport (innerHeight) from the total height (scrollHeight) */const maximumTopScroll = body.scrollHeight - window.innerHeight;// calculating the scroll fractionconst scrollFraction = topScroll / maximumTopScroll;// setting an arbitrary RGB color code as the starting colorconst [red, green, blue] = [173, 216, 230];// calculating the rgb values based on the scroll fractionconst bColor = `rgb(${Math.round(red * scrollFraction)},${Math.round(green * scrollFraction)}, ${Math.round(blue * scrollFraction)})`;/* setting the backgroundColor to bColor for smooth colortransition on page.*/body.style.backgroundColor = bColor;});
Line 4: A constant variable called topScroll
is declared and assigned the current vertical scroll position of the webpage.
Line 8: A constant variable called maximumTopScroll
is declared and assigned the maximum possible scroll height of the webpage by subtracting the visible height of the webpage (body.scrollHeight
) from the total height of the webpage (window.innerHeight
).
Line 11: A constant variable called scrollFraction
is declared and assigned the fraction of the scroll that represents how much of the page has been scrolled. This scroll fraction will be used to calculate the different RGB values based on the webpage scroll.
Line 14: An arbitrary set of RGB values (light blue, in this case)
Lines 17–18: A constant variable called bColor
is declared and assigned the different red, green, and blue values by multiplying the initial values with the current scroll fraction. Math.round
function rounds the resulting RGB values to the nearest integers.
Line 22: The backgroundColor
(property of the body
) is assigned the calculated bColor
based on the current scroll position.
Free Resources