jQuery Background Image Animation

In this tutorial we are going to do HTML background image animation by using jQuery and CSS. In previous tutorial we have seen about HTML div auto load 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 DemoDownload

HTML Code for Background Animation

This code contains animated background image and a control to change the direction the scrolling 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.

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

This function is used for change the direction of background image animation.

function changeDirection() {
	if($("#direction").val() == 'y') $("#direction").val('x');
	else $("#direction").val('y')

View DemoDownload

This jQuery code tutorial was published on December 3, 2014.

↑ Back to Top