Animated background image with jQuery

In this example, we are going to create a basic web page layout which includes a super cool animated background image, using jQuery.


Let’s do it

1. The first step of this tutorial is to download our background image. I have used this one from Twitter, but of course feel free to use any other image you’d like.

2. Once finished, let’s create a a file called index.html. In order to get started with the basic HTML structure, paste the following code in your file:

Animated background Image

3. Now, let’s define our document structure. Since we want to do a simple layout, we’ll only need to create a header and content area. Paste the following within the and tags:

4. Well done! We already have our XHTML. Now, what we have to do is obviously use some CSS and give style to our document.
To do so, copy the code below and paste it within the and tags of the index.html file.

background-color: #C0DEED;

background: #8EC1DA url(bg-clouds.png) repeat-y scroll left top;

#header h1{
font-family: "Myriad Pro", Helvetica, Arial, sans-serif;

margin:25px auto 0 auto;

5. At this point, you can save your work and take a look at the index.html page using your web browser. If everything is ok, your index.html page should look like the screenshot above, with fixed clouds, of course.

6. Now, it’s time to give life to the layout by using the power of jQuery. As you probably guessed it, what we have to do right now is include the library. Since Google hosts a version that you can use, there’s definitely no need to download a copy. Just use the one from Google.

To do so, paste the following line of code in your index.html file, after the closing tag:

7. Now that jQuery has been loaded, we can code a function to animate the background. Copy the code below and paste it on your index.html file, just after the line where you imported jQuery into the file.

var scrollSpeed = 70;
var step = 1;
var current = 0;
var imageWidth = 2247;
var headerWidth = 800; 

var restartPosition = -(imageWidth - headerWidth);

function scrollBg(){
current -= step;
if (current == restartPosition){
current = 0;

$('#header').css("background-position",current+"px 0");

var init = setInterval("scrollBg()", scrollSpeed);

There’s nothing really hard with that code. First, we declare a set of variables to control the animation (image width, scroll speed, etc). Then, we created a function to automatically move the background. The most tricky part is to calculate when we need to reset the position. If you have a better idea about doing it, let me know in a comment! ;)


Be Sociable, Share!

Leave a comment