jQuery Background Image Animation

In this tutorial, we are going to do HTML background image animation by using jQuery and CSS. In the previous tutorial, we have seen about HTML div autoload using jQuery AJAX for banner animation.

In this tutorial, we are animating image background by scrolling in vertical or horizontal direction. We are doing this by changing x or y position of the background image based on the direction selected.

View Demo

HTML Code for Background Animation

This code contains animated background image and a control to change the direction the scrolling animation.

jquery-background-animation

<div id="scroll-bg">
	<h2>Scrolling Background</h2>
</div>
<input type="hidden" id="direction" value="y" />
<input type="button" id="btnAction" value="Change Direction"
	onClick="changeDirection();" />

jQuery Image Background Animation

This code contains two functions. The scrollBg() function is used to change the background image position by using jQuery. In the function, we have used Javascript setInterval() to change position for every 10 seconds.

let intervalid;
function scrollBg() {
	var x = 0;
	var y = 0;
    intervalid=	window.setInterval(function() {
		$("#scroll-bg").css("backgroundPosition", x + "px" + " " + y + "px");
		if($("#direction").val()=='x') x--;
		else y--;
	}, 10);
}
function changeDirection() {
    window.clearInterval(intervalid);
	if($("#direction").val() == 'y') $("#direction").val('x');
    else $("#direction").val('y')
    scrollBg();
}
scrollBg();

The changeDirection() function is used to change the direction of the background image animation. It toggles the axis between x, y on clicking the “Change Direction” button.
View DemoDownload

Photo of Vincy, PHP developer
Written by Vincy Last updated: October 7, 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?