jQuery on Scroll Background Animation

In this tutorial, we are going to see how to create background color animation on page scroll. In the previous article, we have seen background image animation.

In this example, we are using jQuery animate() function to do background animation effect. We are using an array of background colors to be changed on page scroll to create gradient background animation.

View DemoDownload

HTML DIV to Apply Background Animation

This DIV element id is specified as a selector to call jQuery animation.

<body>		
    <div id="bg-animate"> </div>
</body>

jQuery Background Animation

This jQuery script is called on page scroll and change the background-color index. The changed index is used to pick the color from the array to change the background=color of the DIV element with gradient animation.

$(document).ready(function(){
	var i = 0;
	var bgColor = [ "#000099", "#003300", "#FF9900", "#FF3366","#CC66FF"];
	$(window).scroll(function() {clearTimeout( $.data( this, "scrollCheck" ) );
		$.data( this, "scrollCheck", setTimeout(function() {
			$("#bg-animate").animate({backgroundColor: bgColor[i]}, 1500);
			if(i < bgColor.length-1) {
				i = i+1 
			} else {
				i = 0;
			}
		}, 250) );		
	});
});

View DemoDownload

Photo of Vincy, PHP developer
Written by Vincy Last updated: July 12, 2022
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).
Explore topics
Need PHP help?