Build Internet has a brand new theme, and that's only the beginning. Read the full story or hide this bar

Crafting an Animated Postcard With jQuery

Crafting an Animated Postcard With jQuery

Nicely illustrated banners are…nice. But why not add a little pizazz by using animation like Flash websites do?

Through Javascript web pages are becoming increasingly less static and all sorts of creative possibilities are opening up.

In this tutorial we will learn the basics of setting up a continuous animation which can be applied pretty much anywhere. Take a peek below to see an outline of what we’ll be learning today.

What You’ll Learn

  • The art of looping animations using setTimeout()
  • How to take advantage of the Easing plugin
  • A new way to spice up your banner

The HTML

Laying down the groundwork is pretty simple, essentially we create a canvas (‘#content’) and center it with ‘#wrapper’ – pretty standard practice. The difference between this and the average layout lies in our use of ‘position:absolute’ to place each image, which is why there isn’t any real hierarchy to all the elements with images.

<div id="wrapper">
   <div id="content">
      <div id="sun"><img src="images/sun.gif"/></div>
      <div id="cloud1"><img src="images/cloud1.png"></div>
      <div id="cloud2"><img src="images/cloud2.png"></div>
      <div id="cloud3"><img src="images/cloud3.png"></div>
      <div id="raft"><img src="images/raft.png"></div>
      <div id="raftripple"><img src="images/raftripple.gif"></div>
      <div id="greetings"><img src="images/greetings.png"></div>
      <div id="stamp"><img src="images/stamp.png"></div>
   </div>
</div>

The CSS

Next up we will want to plug in all the CSS, I have included comments below to block out the importance of each style.

*{ margin:0; padding:0; }
body { text-align: center; background: #111; }

//Width should match that of the child element #content
#wrapper{ margin:0px auto; width:700px; }

//The canvas for our postcard, must be position:relative/overflow:hidden
#content{ position:relative; width:700px; height:300px; top:30px; overflow:hidden; border:5px solid #f5f5f5; background: url('images/scene_bg.jpg'); }

	#sun{ position:absolute; top:10px; left:30px; }

	//Note the negative left values that hide the clouds offscreen
	//The z-indexes define how the clouds with stack on top of each other
	#cloud1{ position:absolute; top:60px; left: -150px; z-index:5; }
	#cloud2{ position:absolute; top:40px; left: -250px; z-index:4; }
	#cloud3{ position:absolute; top:25px; left: -100px; z-index:3; }

	//Our raft/ripple under the raft, z-indexes stack them accordingly
	#raft{ position:absolute; top:220px; left: 312px; z-index:20; }
	#raftripple{ position:absolute; top:220px; left: 309px; z-index:19; }

	//The text and stamp both positioned off-screen and on top of everything
	#greetings{ position:absolute; top:-51px; left: 200px; z-index:21; }
	#stamp{ position:absolute; top:5px; left: 801px; z-index: 21; }

At this point in the game you should be looking at something pretty similar to this:

Get Your jQuery Ready

For those of you that aren’t as familiar with the whole jQuery scene we’re going to need to tag the following two lines into the <head> of the page:

<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script src="jquery.easing.1.3.js" type="text/javascript"></script>

The first line calls jQuery, but the second calls the Easing Plugin, which might not be as familiar to you. We will be making use of it later in the tutorial, so for convenience sake, I have provided it in the downloadable files. If you’re one of those independent folks you could download it from the official site too, I won’t be offended.

The Basic Template for Looping an Animation

Below I have outlined the format for making a function that does a looped animation, in this case it is called the rather ambiguous name – ‘animate_element’.

function animate_element(){
 $("#element").animate({left:"+=100px"},1000).animate({left:"-=100px"}, 1000)
 setTimeout("element()",2000);
}

If we pay attention the the first line of code within the function, we can see that it runs two animations, one after the other.

$("#element").animate({left:"+=100px"},1000).animate({left:"-=100px"}, 1000)

The first of the two moves the element 100px from the left relative to it’s current location – as denoted by the ‘+=’. When that animation is complete the next will be triggered, which does the exact opposite and moves the element back to it’s starting location.

When the animations finish then we want to have the same function called again, so that they will be repeated. We do this via setTimeout(), which can trigger events based on a timer.

setTimeout("element()",2000);

The key point to notice is that the timer (2000 in this case) should be the sum of all the animation times in the previous line. This essentially will allow for each of the animations to complete (1000 + 1000), before restarting the function.

Creating Looped Animations for Our Postcard

After having just educated yourself in the setup for an animation, you should be be more than qualified to follow along in this next step, where we define a series of animation loops. Instead of doing a separate function for each individual animation, those that take the same amount of time to complete can be grouped together.

function sun_raft(){
	$("#sun").animate({opacity:".7"},1000).animate({opacity:"1"},1000);
	$("#raft").animate({top:"-=5px"},1000).animate({top:"+=5px"}, 1000);
	$("#raftripple").animate({opacity:".1"},1000).animate({opacity:"1"},1000);
	setTimeout("sun_raft()",2000);
}
function cloud1(){
	$("#cloud1").animate({left:"+=850px"},10000).animate({left:"-150px"}, 0)
	setTimeout("cloud1()",10000);
}
function cloud2(){
	$("#cloud2").animate({left:"+=950px"},9000).animate({left:"-250px"}, 0)
	setTimeout("cloud2()",9000);
}
function cloud3(){
	$("#cloud3").animate({left:"+=800px"},6000).animate({left:"-100px"}, 0)
	setTimeout("cloud3()",6000);
}

In the instance of the clouds, which will be constantly scrolling across the screen, after they travel the distance, they are reset to their initial location via an animation that takes 0 time (therefore instantaneous).

The raft portion of the postcard has two animations going side by side – The raft bobs up and down, while the ripple underneath fades in and out.

Putting It All Together (in a Function)

Now that we’ve defined the animations that will be looping let’s combine them all into a function that we can then call when the page loads.

function animation(){
	sun_raft();
	cloud1();
	cloud2();
	cloud3();
}

Wonderfully simple. Now instead of having to type out 4 different functions each time, we can simply call animation().

Adding One Time Animations & The Easing Plugin

Within our animated postcard we don’t necessarily want everything looping – in this example we only want the “Greetings from Build Internet!” and stamp to animate once. In order to accomplish this, we’re just going to tack the following two lines onto the end of the animation():

$("#greetings").animate({top: '125px' }, {queue:false, duration:600, easing:'easeOutBounce'});
$("#stamp").animate({left: '595px' }, {queue:false, duration:1200, easing:'easeOutBounce'});

You might have noticed the extra stuff built into animate(), don’t panic, that’s the Easing Plugin we talked about before doing it’s job. There are a number of options to play with, but for this example I’ve opted for a bounce effect when the text and stamp roll in, it adds some nice flair.

Time To Set It Off

We’ve got everything in order we need to actually have an event trigger animation(), I want it to begin as soon as the page loads, so this is what mine will look like:

$(document).ready(function() {
	setTimeout("animation()",300);
});

Special Note : You may have noticed I added a setTimeout() before calling animation() – This is so the visitor/browser have time to get situated before firing off the animations. If your animations are triggered by a click or something of that nature, you won’t need to encase animation() in a setTimeout().

Your Postcard Is Ready

Consider yourself armed with knowledge, obviously there are a fair share of creative applications for looped animations, so get cooking! For those of you craving more, check out the CSS-Tricks article called Building an Animated Cartoon Robot with jQuery.

Wordpress.com stats not installed! Posted Monday, August 10th, 2009 / Back to Top

I this post. Tweet
SPONSOR

76 Comments 107 Mentions

  1. Brian Klepper Author Editor

    Excellent work! I am currently working on a small project using similar functions. Thanks for the post
    .-= Brian Klepper´s last blog ..Steal Everything Excerpt =-.

    August 10, 2009 · Reply

  2. Robert Fisher Author Editor

    Great tutorial! I can imagine how this code can be used for other projects.
    .-= Robert Fisher´s last blog ..Math Resources Online =-.

    August 10, 2009 · Reply

  3. Hezi Author Editor

    rocknroll!
    .-= Hezi´s last blog ..HeziAbrass: Probably the most impressive animated gif ever http://bit.ly/PEUTs =-.

    August 10, 2009 · Reply

  4. mrvn Author Editor

    cool stuff. very useful for many other things too!!
    .-= mrvn´s last blog ..Artcore die Zweite =-.

    August 10, 2009 · Reply

  5. anil singh Author Editor

    Useful and intersting info

    August 10, 2009 · Reply

  6. Raja Sekharan Author Editor

    Great tutorial Sam. There is a similar implementation using mootools here:

    http://devthought.com/

    The clouds disappear when you click on them and can be dragged around. Really nice effect.
    .-= Raja Sekharan´s last blog ..How To Create Custom Forms Using Drupal In 4 Easy Steps =-.

    August 10, 2009 · Reply

  7. choen Author Editor

    ow. i liked. thanks… I want to try this tutorial
    .-= choen´s last blog ..Menggunakan sIFR 2.0 di ‘Blogger Template’ =-.

    August 10, 2009 · Reply

  8. tiff Author Editor

    Great tutorial!
    But where can I found (background-)images like this?

    August 11, 2009 · Reply

  9. webmasterdubai Author Editor

    wowo great work nice tutorial anybody can think its flash but is jquery.

    August 13, 2009 · Reply

  10. Jason Author Editor

    Awesome tutorial! I love how jQuery can be used in place of flash in many cases.
    .-= Jason´s last blog ..Creating Blind Accessible Web Sites and Applications =-.

    August 14, 2009 · Reply

  11. Sam Dunn Author Editor

    Thanks for the great feedback everyone.

    @tiff
    I created all of these background images specifically for this tutorial

    August 16, 2009 · Reply

  12. Scott Author Editor

    Would love to see how to do this on a div that is fluid and goes across the whole screen.

    August 17, 2009 · Reply

  13. Anthony Calzadilla Author Editor

    Excellent article Sam! You’ve inspired me to re-visit my jQuery robot and try to up the ante of jQuery animation.

    Thanks!
    Anthony
    .-= Anthony Calzadilla´s last blog ..Let’s Word Out Key Terms Like XHTML, jQuery and CSS =-.

    August 31, 2009 · Reply

  14. Luciano Santa Brígida Author Editor

    Hi, I loved this tutorial and easily built a banner like this one here. But when I published to the web I experienced a conflict with the jquery cycle plugin, which is also called by using jQuery(document).ready(function($) { $(“#rotator”).cycle({fx: ‘fade’, timeout: 6000, }); });
    When I remove those lines the banner animation goes ok. Any ideas on how to solve this?

    August 31, 2009 · Reply

  15. Luciano Santa Brígida Author Editor

    I figured a partial solution: I replaced $(document).ready(function() {} ) for $(window).load(function() {} )

    But unfortunately, it didn’t work on Chrome. IE and FF are OK, only tested in these 3 so far.

    Question: if I used setInterval instead of setTimeout, would I achieve the same loop effect? Could this fix the Chrome problem?
    .-= Luciano Santa Brígida´s last blog ..Dicionário Twitter =-.

    August 31, 2009 · Reply

  16. Amy Author Editor

    Awesome tutorial, now all we have to do is set the background color to change based on the time of day, and make the tube bob up and down in response to the user’s mouse movements, and we’re really cooking!

    September 1, 2009 · Reply

  17. bayXSonic Author Editor

    ooo ugly setTimeout!
    Im working on a project now and I came up with this:
    function pulse(selector){
    $(selector).animate({opacity:.7}, 500).animate({opacity:.9}, 500, function(){pulse(selector)});
    }

    But I’m sure that it can be improved much more.

    November 29, 2009 · Reply

  18. Vishal Modha Author Editor

    I’ve taken this a few steps further by adding an interactive Santa to the mix with the use of the sound plugin….

    Check it out here and tell me what you think:
    http://modasoft.co.uk/ecard.html

    Thanks for this article, it’s been a great stepping stone.

    December 18, 2009 · Reply

  19. Mike Croteau Author Editor

    Very cool… plan on playing around with this!

    January 30, 2010 · Reply

  20. Marc Author Editor

    Thanks! A good big start for my project.

    Also I found a way that does not have the bug (in my case) of not appearing if opacity is set lower than .7.
    We can manipulate in time opacity parameter!

    I use:

    duration=2000;
    opacity=.2;
    $(‘xyz’).fadeTo(duration,opacity);

    April 1, 2010 · Reply

  21. viqizevic Author Editor

    Nice tutorial!!
    Awesome! Super!
    ^_^

    May 28, 2010 · Reply

  22. saduran Author Editor

    hi firstly tnx for this great Tutorial , i have one question how can i change clouds speeds ?

    June 5, 2010 · Reply

  23. saduran Author Editor

    ok i have solved problems :) tnx again

    June 5, 2010 · Reply

  24. SexyContent Author Editor

    So creative!
    Simple but effective. Thanks!

    July 22, 2010 · Reply

  25. tokat nakliyat Author Editor

    good code thanks

    August 14, 2010 · Reply

  26. Phil_M Author Editor

    Really Great Tutorial!!
    Thanx!!

    August 31, 2010 · Reply

  27. Xtence Author Editor

    Nice ! who needs flash anyway !

    Great tutorial

    September 9, 2010 · Reply

    • Charl Author Editor

      Wow, that’s a really clever way of tnihking about it!

      May 16, 2011 · Reply

  28. oyun haberleri Author Editor

    great… thanks for sharing.

    September 13, 2010 · Reply

  29. guille Author Editor

    Great Efect! I Love JQuery!

    October 10, 2010 · Reply

  30. Nano Author Editor

    thanks… :)

    November 12, 2010 · Reply

  31. Valikonen Author Editor

    Very cool effect, thanks!!! If you want to see gallery and menus, visit http://www.1artmedia.com, you have online demo and free download, bye!

    December 10, 2010 · Reply

  32. Greta Author Editor

    Really Nice…..

    January 7, 2011 · Reply

  33. Creación Web Author Editor

    Si es cierto es buen programa el jquery para dar vida a una web, lo hace ver bonito buen post.

    Saludos…

    January 21, 2011 · Reply

  34. bazafrogg Author Editor

    merci beaucoup,
    this tut is very useful

    February 3, 2011 · Reply

  35. ดูซีรี่ย์ Author Editor

    Very cool effect

    February 5, 2011 · Reply

  36. Dantel Author Editor

    Do you have a live demo? also could not see? Thanks.

    April 9, 2011 · Reply

  37. ann Author Editor

    good work!

    April 24, 2011 · Reply

  38. web design uae Author Editor

    Thanks for the awesome tutorial.

    June 2, 2011 · Reply

  39. Jon Author Editor

    How can I see this in action? I can’t seem to see it in Chrome or FF4.

    June 2, 2011 · Reply

  40. Dortcelik Cocuk Hastanesi Randevu Alma Author Editor

    Thanks for sharing and keep up the good work. That is a great article.

    June 19, 2011 · Reply

  41. Catzie Author Editor

    This is very interesting. It makes me prefer jQuery over Flash even more.

    June 20, 2011 · Reply

  42. cabal Author Editor

    Knocked my socks off with !

    June 28, 2011 · Reply

  43. Igor Author Editor

    Sample ? :)

    July 27, 2011 · Reply

  44. طراحی وب سایت Author Editor

    Thanks for posts

    July 31, 2011 · Reply

  45. Ye Ko Author Editor

    Great !!!!

    August 9, 2011 · Reply

  46. Tidy Design Author Editor

    One word… AWESOME!

    August 10, 2011 · Reply

  47. genn Author Editor

    You are brilliant! I’ll be needing this for my portfolio site.. Thank you heaps! :) Continue to shine on!

    September 7, 2011 · Reply

  48. Raja Author Editor

    Superb!!!!111

    September 17, 2011 · Reply

  49. Frank Author Editor

    Where is the demo? It seems to be a dodgy site making people click on that advert on top…

    September 26, 2011 · Reply

  50. طراحی سایت Author Editor

    Nice tutorial!!
    Thanks

    October 12, 2011 · Reply

  51. test Author Editor

    test

    October 25, 2011 · Reply

  52. rift platinum Author Editor

    Look like cool plugins, lots of functionalities in a single plugins. news letter plugin is a sparky one among theme. Hope i will get a chance to grab them for free

    November 2, 2011 · Reply

  53. moedas pw Author Editor

    Hi everyone, thank you for your support. The contest is closed.

    The winners are listed at the end of this article. Thank you!

    November 2, 2011 · Reply

  54. Builders in chennai Author Editor

    Great ! I am just working on a similar one like this and searched all over the net and found yours.Thanks for the share.

    November 9, 2011 · Reply

  55. kirth Author Editor

    Hello, your tutorial is awesome and i managed my animation so far ok. I have only a small problem, i don’t want the little pause from first animation to the second and to the final third.

    My code is:

    $(“.ie .moon”).animate({left:”+=230px”,top:”+=-180px”},15000).animate({left:”+=330px”,top:”+=-30px”},15000).animate({left:”+=270px”,top:”+=-45px”},15000)

    it has 3 movements, first leftTop, then leftTop again and the final leftTop. It’s animating a rising moon across the screen, from bottom right to topleft, and it’s beautiful. But i want the three animation smoothing together, not the three little pause.

    December 8, 2011 · Reply

  56. طراحی سایت و سئو Author Editor

    very great man tnx

    December 12, 2011 · Reply

  57. Carina Author Editor

    I haven’t got any experience with JQuery. What are the advantages? What makes it better than Flash?

    December 12, 2011 · Reply

  58. Social media Author Editor

    Wow its really awesome jQuery tutorial. Nicely explained all code. And play very smoothly. Thanks for sharing.

    December 29, 2011 · Reply

  59. Maryjo Bergey Author Editor

    Really nice pattern and excellent content , nothing at all else we want : D.

    January 30, 2012 · Reply

  60. website designing in chennai Author Editor

    Good Work. This is really excellent

    February 3, 2012 · Reply

  61. قیمت آهن آلات Author Editor

    you are great and thank for your articles.

    February 4, 2012 · Reply

  62. gavin Author Editor

    Thanks for sharing . Will try to use some the effects in my next website .
    http://www.gavinmendes.co.in

    February 12, 2012 · Reply

  63. طراحی سایت Author Editor

    This is very interesting. It makes me prefer jQuery over Flash even more.

    February 22, 2012 · Reply

  64. Boyd Author Editor

    Quite a difficult for me to understand, but i stll like it.

    February 24, 2012 · Reply

  65. يوتيوب Author Editor

    You are great and thank for you articles

    March 6, 2012 · Reply

  66. شات صوتي Author Editor

    thank for you articles

    March 6, 2012 · Reply

  67. Juan Caonth Author Editor

    Hello !

    March 11, 2012 · Reply

    • Ana Author Editor

      Wonderful beat ! I would like to apprentice while you amend your web site, how could i crssbuibe for a blog web site? The account aided me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear idea Many thanks,

      March 20, 2012 · Reply

  68. Pitso Author Editor

    Very helpful…. thanks!

    March 24, 2012 · Reply

  69. Biuro Podrozy Author Editor

    I just needed to say that I found your website via Goolge and I am glad I did. Keep up the good work and I will make sure to bookmark you for when I have more free time away from the books. Thanks again!

    March 24, 2012 · Reply

  70. Piano Bench Author Editor

    For some reason I felt relieved about my decision on getting a new Piano Bench For Sale just after looking through your post. Carry on and shed light on other individuals by spreading your ideas I’ll be one of the people that will constantly there to help cheer you up.

    March 25, 2012 · Reply

  71. Ben Author Editor

    Great tutorial! I am going to use it for my personal site but am having trouble resetting animated diagonal objects, they just continue downwards and upwards. New to JQuery so sorry for the simpleton apprioach. Thanks!

    April 27, 2012 · Reply

  72. obuwie damskie Author Editor

    I this way web blog greatly, Its a really nice billet to read and get info. If in the beginning you don’t succeed, you’re operating about typical. by M. H. Alderson.

    April 29, 2012 · Reply

  73. Shingo Author Editor

    Nice! You might already know this but you can set the function to be called by setTimeout like this as well:

    setTimeout(sun_raft, 2000);

    Cheers

    May 13, 2012 · Reply

  74. Luthfi All Author Editor

    wow.., it’s so great..
    I have try..
    thanks so mch

    May 20, 2012 · Reply

 

Join the Conversation

Back to Top / Comment RSS

2012 Build Internet. Created by One Mighty Roar. Icons by Komodo Media. Back to Top