jQuery Background Image Animation

by Vincy. Last modified on October 7th, 2022.

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

↑ Back to Top

Share this page