Changing a webpage’s background color on a scroll is an exciting feature that improves UX. Developers can implement this feature with the technology of their choice. This Answer explains how to do it with jQuery.
To change the background color on a scroll using jQuery, we can bind an event handler to the scroll event and modify the CSS properties dynamically. Here’s an example:
Line 6: The scroll
event handler, runs its callback function in response to the page scroll.
Line 7: We create the scroll
constant. It holds the vertical scrollbar position.
Line 9: We create a threshold and assign it to the variable scrollThreshold
.
Lines 12–13: We assign two different colors to two different variables backgroundColor1
and backgroundColor2
.
Line 16: We create a variable that holds a conditional statement. If scroll
is greater than scrollThreshold
, then backgroundColor2
is true, otherwise, it’s backgroundColor1
.
Line 19: We apply the background color to the body element to change the body’s CSS background to backgroundColor
.
When the user scrolls past the scrollThreshold
value (in this case, 100
pixels), the background color of the body element will change to backgroundColor2
. Otherwise,backgroundColor1
will continue to be used. The background colors are transitioned seamlessly using the CSS transition attribute transition: background-color 0.5s ease
.
Note: Remember to place the jQuery library before the JavaScript code in your HTML file.
Free Resources