How to change the background color on scroll using jQuery
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.
Code example
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:
Explanation
-
Line 6: The
scrollevent handler, runs its callback function in response to the page scroll. -
Line 7: We create the
scrollconstant. 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
backgroundColor1andbackgroundColor2. -
Line 16: We create a variable that holds a conditional statement. If
scrollis greater thanscrollThreshold, thenbackgroundColor2is true, otherwise, it’sbackgroundColor1. -
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