If you're used to work with the jQuery library, there's no doubt that you know how powerful it is. In this tutorial, we are going to create a basic web page layout which includes a super cool animated background image, using jQuery.

Getting ready

In this tutorial, we are going to create a simple layout for a website, which includes a very cool animated background. Here is how the final result will look:

As you can see, in this example I have used the Twitter background clouds, which look really nice.
This tutorial has been inspired by the one called How To Build an Animated Header in jQuery that I definitely recommend you go check out.

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:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
		<title>Animated background Image</title>
	</head>

	<body>
	</body>
</html>

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 <body> and </body> tags:

<div id="container">
	<div id="header">
		<h1>Animated Background Image</h1>
	</div><!-- #header -->

	<div id="content">
		<!-- Your content will go here -->
	</div><!-- #content -->
</div><!-- #container -->

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 <head> and <head> tags of the index.html file.

<style type="text/css" media="screen">
	body{
		background-color: #C0DEED;
		margin:0;
		padding:0;
	}

	#header{
		height:180px;
		background: #8EC1DA url(bg-clouds.png) repeat-y scroll left top;
		text-align:center;
		margin-top:-30px;
	}

	#header h1{
		padding-top:35px;
		font-family: "Myriad Pro", Helvetica, Arial, sans-serif;
		color:white;
		font-size:45px;
	}

	#content{
		background-color:#fff;
		height:500px;
		width:980px;
		margin:25px auto 0 auto;
		-moz-border-radius:10px;
		-webkit-border-radius:10px;
	}
</style>

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 </body> tag:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>

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.

<script type="text/javascript" charset="utf-8">
	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);
</script>

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! ;)

Demo & Download

I hope you enjoyed this tutorial and helps you to create very nice websites. If you want, you can see a Demo of this code, or you can Download the source files.

 

52 Comments

  1. Posted November 12, 2009 at 2:25 am | Permalink

    Awesome tutorial! Just tweeted it.

  2. Posted November 12, 2009 at 2:44 am | Permalink

    Very nice little jQuery trick.

  3. Posted November 12, 2009 at 3:03 am | Permalink

    Great tutorial Jean, this is just another step towards flash dying.

    The image doesnt get added until there is enough space for it so there is a gap every 20 seconds or so. See this screenshot:

    http://screencast.com/t/MTZiMjNkO

    Firefox 3.5

  4. Posted November 12, 2009 at 3:12 am | Permalink

    Looks very cool! I would just make it move slower, to make it less distracting.

  5. Posted November 12, 2009 at 5:06 am | Permalink

    Brilliant! this looks wicked! thanks for the tut.

  6. Mark
    Posted November 12, 2009 at 7:31 am | Permalink

    This is sexy, for real.

  7. John
    Posted November 12, 2009 at 8:03 am | Permalink

    Wes – I fixed it with changing var imageWidth = 2247; to var imageWidth = 1700; but I assume you could change the headerWidth also.

    Does this have increased CPU usage because I tested it and it revved up my processor pretty good. Maybe it’s just me?

  8. Posted November 12, 2009 at 10:28 am | Permalink

    Nice tip, thanks for sharing on Twitter ;)

  9. Posted November 12, 2009 at 12:11 pm | Permalink

    Great, but is there very usefull to load jquery just for this animation?

    It’s really easy to use default function and speed up the execution time (while not using jquery somewhere else ofc) of the script by changing line 73 into :
    document.getElementById(’header’).style.backgroundPosition = current+’px 0′;

    If you’re using Prototype or Mootools :
    $(’header’).setStyle(”background-position”,current+”px 0″);

  10. Posted November 12, 2009 at 12:30 pm | Permalink

    Great tutorial!

    Currentry I’m working on the same approach for one of the project – and I’ve met at least two small problems, that was not covered in your tutorial (as for myself I have not found any optimal solution for them yet)…

    1. When the cycle ends end animation restarts there is visible jump in image… When we dealing with vertiacal moving that easily could be fixed with the same pixel-set in the beginnig and in the end of animation that equal to the header height, but in the horizontal case it does not work because we don’t now the width of user’s window in this moment and this width is different for different users

    2. In your case restart position is calculated assuming that the header width is 800px, but if user has screen resolution more than 800*600 – this put you in a trouble because the user will see the end of the picture moving on the screen before the animation restarts… so there we also meet the question about user’s screen width

    probably further discussions will reveal some solutions :)
    anyway thank you a lot for sharing this code :)

  11. Posted November 12, 2009 at 1:46 pm | Permalink

    Thanks for this list :)

  12. InTRUEdeR
    Posted November 12, 2009 at 7:35 pm | Permalink

    “var headerWidth = $(’html’).width();” will work with any screen resolutions, but headerWidth need to be updated inside script when user resize window.

  13. Posted November 13, 2009 at 8:54 am | Permalink

    F*%$ awesome man!!!
    I wanna implement it someday :/
    i’ll twit it right away

  14. bionickid
    Posted November 13, 2009 at 11:59 am | Permalink

    does NOT work. reaches the images end.

  15. Posted November 13, 2009 at 3:35 pm | Permalink

    Can you tell me if we can use the twitter background on our projects?

  16. Posted November 13, 2009 at 7:42 pm | Permalink

    By the way, you can determinate the screen resolution with: screen.width

    You just need to put it like this: var headerWidth = screen.width;

    There you go! :D

  17. John
    Posted November 15, 2009 at 7:00 am | Permalink

    This needs to use clearInterval, doesn’t it? CPU runs to 100% the longer this runs. Anybody know how to do it?

  18. Posted November 15, 2009 at 11:07 am | Permalink

    That’s some nice jQuery!

  19. Posted November 17, 2009 at 10:24 am | Permalink

    i want to know if we can use the twitter background on our projects?

  20. Posted November 17, 2009 at 4:25 pm | Permalink

    @jane : I don’t think you can since the example image I took comes from Twitter website.

  21. Posted November 17, 2009 at 9:04 pm | Permalink

    too good! loved it! love jquery!

  22. Bev
    Posted November 18, 2009 at 8:36 am | Permalink

    Could you please show me I would incorporate this into a wordpress site please?

  23. Posted November 19, 2009 at 4:55 pm | Permalink

    hi don’t forget to check another inspiration at my web site click product and choose another design and after that choose my type…i have another animation for background just with jquery..i really like it..and i really like your web site name “catswhocode” ,thankyou..

  24. Posted November 19, 2009 at 7:55 pm | Permalink

    Thanks for the tip. I think I’m going to use it for my site.
    I’ll modify it and embedded it in the middle of the page.

    Thanks.

  25. Posted November 20, 2009 at 10:44 am | Permalink

    Wow. Great one. I’ll definitely use this for my personal website.

  26. Posted November 21, 2009 at 9:12 am | Permalink

    don’t think you can since the example image I took comes from Twitter website.

  27. Posted November 22, 2009 at 5:58 am | Permalink

    This is pretty slick, thank you for sharing it.

    To make the animation seamless could you use two exact images that rotate positions?

    For example as image1 is halfway through it’s animation, image2 would append to the end of image1.

    When image2 moves completely into the background space, image1 would append to the end of image2.

  28. Posted November 22, 2009 at 5:14 pm | Permalink

    Well done! That’s a really useful tutorial.

  29. Posted November 23, 2009 at 6:09 pm | Permalink

    I dont know much yet in jquery but this tutorial rocks!

  30. Posted November 27, 2009 at 3:27 pm | Permalink

    Woww. Thank you so much Jean.

  31. Posted November 28, 2009 at 4:29 am | Permalink

    awesome tuts..thanks for share

  32. Posted November 29, 2009 at 7:51 am | Permalink

    Awesome trick – worked for me too..

    any way to do it with a flash file ? maybe a negative z-index or something ?

  33. Kapil
    Posted November 30, 2009 at 11:09 am | Permalink

    Thanks alot for the neat trick. I am planning to do something similar with my personal site with some extra parameters. But this one saved me alot of coding time. :)

  34. Posted December 3, 2009 at 12:13 pm | Permalink

    Wow, first time I saw an effect like this. I thought things like this are exclusive for flash websites only. I’m definitely exploring this trick. I just might incorporate it in some sites of mine. Thanks a lot.

  35. Posted December 6, 2009 at 10:50 am | Permalink

    Hmm, nice start but this needs some work.

    At first I would make it go slower, which will make it less distracting. Then second, as mentioned before, it jumps when it reaches the end, so you should get the screen width and work with that value.

    Third, some people say it gets their CPU really pumped up and that’s not what we want right.

    Nice start!

  36. Posted December 17, 2009 at 6:42 am | Permalink

    Here’s my solution for the time being:

    If you open the ‘bg-clouds.png” in Photoshop and tile the clouds to something like the width of 6741pixels and re-save it, it’s only a 100kb image still. Set the “var scrollSpeed = 70;” and you’re all set.

    Now, the kick doesn’t come in for a looooong time ;)

  37. Posted December 29, 2009 at 12:31 pm | Permalink

    The very cool, thanks !

  38. Posted December 30, 2009 at 7:19 pm | Permalink

    what amazing beautiful tutorial…, don’t need more flash for this animation
    Thank you so much =)

  39. Posted January 9, 2010 at 1:47 am | Permalink

    Great tute, and nice code. Would love to see this with multiple depth, like parallax scrolling, so, back mid front.

    Great blog, and thanks for sharing, Digging now =)

  40. chinoke
    Posted January 21, 2010 at 5:34 pm | Permalink

    I just want to say that Cats are really good in writing codes “art of code” after what i read in this website; Gratz

  41. PaulO
    Posted January 24, 2010 at 4:28 pm | Permalink

    Here’s a way to get around the end of image problem:

    1. Use an image that can wrap horizontally.
    2. Add to the background style “repeat-x”.
    3. Update this line of code: “var restartPosition = -(imageWidth);”

    It’s a cool effect, but still trying to figure out if I should use it or not.

  42. Posted March 3, 2010 at 4:33 am | Permalink

    Another useful article!
    Jean-Baptiste, your whole blog is really great. Everytime I have a new idea, I keep coming back here and chances are you already covered it with a great tutorial.
    Like this one.
    Thanks.

  43. dante
    Posted March 8, 2010 at 12:58 pm | Permalink

    Hey man, awesome tut.
    I tried to modify it so it scrolls vertically, but then IE gives me an error (I don’t care about error itself, but it wont animate in IE) in Jquery.1.4.2.js, whether it’s hosted on google or by me… weird stuff.

    here’s the code:

    var scrollSpeed = 70;
    var step = 1;
    var current = 0;
    var imageHeight = 458;
    var headerHeight = 1000;
    var restartPosition = -(imageHeight – headerHeight);
    function scrollBg(){
    current -= step;
    if (current == restartPosition){
    current = 0;
    }
    $(’#logo3′).css(”background-position”,”0″+current+”px”);
    }
    var init = setInterval(”scrollBg()”, scrollSpeed);

    please help!! :( (((

    • Posted August 11, 2010 at 10:32 am | Permalink

      I used the vertical image animation and it works:

      /* vertical animation */

      var scrollSpeed = 300;
      var step = 150;
      var current = 0;
      var imageHeight = 1350;
      var headerHeight = 150;

      var restartPosition = -(imageHeight);

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

      $(’#animation’).css(”background-position”,”0 “+current+”px”);
      }

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

      • Eric
        Posted August 19, 2010 at 1:24 pm | Permalink

        How do you make the background go to the right vs. left?

  44. dante
    Posted March 8, 2010 at 1:51 pm | Permalink

    OK NVM I did it!11

    I just copied code again and after careful analysis it seems that I had deleted empty space after zero:

    $(’#logo3′).css(”background-position”,”0″+current+”px”);

    now it’s like:

    $(’#logo3′).css(”background-position”,”0 “+current+”px”);

    and it works.
    I can’t believe how much SUCK IE contains, but ok.
    sorry for useless posts. :D

    great tut again, btw.

  45. Posted May 20, 2010 at 12:06 pm | Permalink

    Wouldn’t be much easier like this?:

    function scrollBar(){
    $(’#header’).css(”background-position”,”0px 0px”).animate({backgroundPosition: “-2247px 0px”},4000,”linear”,scrollBar);
    }

    $(function(){
    scrollBar();
    });

    :)

  46. Posted May 20, 2010 at 12:12 pm | Permalink

    Also, changing the background repeat to just “repeat” for it to repeat horizontaly as well.

    Cheers

  47. Posted June 26, 2010 at 6:17 pm | Permalink

    This is very inspiring. I’m learning a lot and realize just how far I have to go!

  48. Posted August 6, 2010 at 10:29 am | Permalink

    Another great tutorial. I like the Twitter background. I previewed the demo and it was great. Looking forward to some more tutorials from you.

  49. Posted August 10, 2010 at 3:54 pm | Permalink

    Hi there,

    Nice code!

    Some changes to continuous move.

    var imageWidth = 2247; // Background image width
    var headerWidth = 1685; // How wide the header is.

    I Hope helped someone

    Bye

  50. Posted August 18, 2010 at 2:18 am | Permalink

    Nice trick!!! Unfortunately the demo links are broken or not found…

15 Trackbacks

  1. [...] Animated background image with jQuery Share and Enjoy: [...]

  2. [...] Enlace | Cats Who Code [...]

  3. By H-Yaman » jQuery ile Hareketli Arkaplan Yapma on November 13, 2009 at 10:35 am

    [...] ulaşacağımız tekniğin nasıl yapıldığını öğrenmek, kaynak kodlara ulaşmak için de şuraya uğramak yeterlidir. Kesinlikle arşive alınması gereken bir döküman olduğu için buraya yazma [...]

  4. [...] Animated background image with jQuery [...]

  5. [...] Animated background image with jQuery If you’re used to work with the jQuery library, there’s no doubt that you know how powerful it is. In this tutorial, we are going to create a basic web page layout which include a super cool animated background image, using jQuery. [...]

  6. [...] 背景画像をアニメーションさせる方法 [...]

  7. By Tutorial: Fondo Animado con jQuey | Editando La Web on November 22, 2009 at 7:20 am

    [...] | Cats Who Code [...]

  8. By Fond animé en jQuery | Live On Design on November 26, 2009 at 10:16 am

    [...] le 26.nov, 2009, catégorie Ajax Si vous désiriez faire un fond animé sur votre site, alors ce tutoriel est pour vous. La démo est [...]

  9. [...] Animated background image with jQuery – Cats Who Code – Nov ‘09 [...]

  10. [...] Animated background image with jQuery – Cats Who Code – Nov ‘09 [...]

  11. By links for 2009-12-08 « toonz on December 9, 2009 at 1:06 am

    [...] Animated background image with jQuery (tags: background jquery effect header) [...]

  12. [...] ulaşacağımız tekniğin nasıl yapıldığını öğrenmek, kaynak kodlara ulaşmak için de şuraya uğramak yeterlidir. If you enjoyed this article please consider sharing [...]

  13. [...] CatWhoCode Bookmark : del.icio.us | Reddit | Slashdot | Digg [...]

  14. [...] 10. Animated Background Image (another!) [...]

  15. By Background with JQuery « LifeBits.Blog on April 7, 2010 at 5:17 am

    [...] 1. Animated background image with jQuery [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting

  • Smashing Network
  • Hosted by VPS.net and Akamai CDN
WordPress Appliance - Powered by TurnKey Linux