<

Simple animation using JQuery

Published on
15,768 Points
5,268 Views
5 Endorsements
Last Modified:
Awarded
Editor's Choice

Requirements

JQuery 1.6+
HTML
CSS

Introduction

This article was inspired by an EE question on how to make a page show some balloons animate up a page. It seemed like a fun exercise so I cobbled something together. It turned out to be surprisingly simple so I thought it might be beneficial to post it here.

The Basics

The problem to solve is to randomly create different coloured balloons at different intervals at different locations on the screen and have them rise up at different speeds to disappear off the top of the screen.

To do this we need some resources

Firstly, a sprite that contains all the different balloon colours we will be using. We could use SVG and create the balloons on the fly but the title of this article is "simple" animation so I will leave that for another article.

Once we have the sprites we will need someway to generate new balloons and having done that a way to animate each balloon after it has been created.

This is where the power of JQuery comes to the fore as we will demonstrate below.

Firstly we need our sprite. Break out the trusty 'ol Gimp and use the ellipse tool to create a nice balloon shape. Then use the path tool to create a nice bezier curve string. I could have just used the pencil or paint tool to draw the string but I like bezier curves.
Next we increase the height of the canvas 4 times and copy the balloon 4 times to 5 new layers one underneath the other to make our sprite. For each layer we use the fill tool to fill the balloon with a different colour.
Balloon Sprite
That done - we need a container for our balloons
<body>
</body>

Open in new window


That's pretty much it. Lets style our container. We want our body to be 100% so our page fills the screen. And we want to make the body overflow: hidden so we don't generate some scroll bars when we start manufacturing balloons below the fold.
body, html {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

Open in new window


Finally we need a container for our balloon. This needs a bit more elbow grease but here is the styling for our balloon container.
div.balloon {
  width: 100px; /* width of our sprite */
  height: 75px;  /* height of our sprite */
  background-image: url(images/balloons.png); /* path to sprite */
  background-position: 0 0; /* default sprite to first */
  background-repeat: no-repeat; /* don't repeat this image */
  position: absolute; /* necessary to be able to position our sprite */
  top: -9999px; /* start it off the page somewhere - probably redundant */
}

Open in new window


That's our sprite done. All that is left is for us to create the factory for our balloons.

The principle behind the animation is to call a function at random intervals that creates a new balloon, adds it to the page, animates it off the page and destroys it.

We do this with a javascript function - call it balloon(). The function will need to perform the following steps
1. Create a balloon element (<div/>)
$('<div/')

Open in new window

2. Assign the balloon class to this div
$('<div/')
  .addClass('balloon')

Open in new window

4. Randomly select which balloon colour to create
5. Position the newly created balloon (left / right of the screen)
We do 4 and 5 in one CSS statement
$('<div/')
  .addClass('balloon')
  .css({top: startheight + 'px', left: leftspace + 'px', backgroundPosition: pos})

Open in new window

6. Animate the balloon towards the top of the screen at a random speed
7. When the balloon passes the top of the screen - remove it from the page.
      $('<div/>')
        .addClass('balloon')
        .css({top: startheight + 'px', left: leftspace + 'px', backgroundPosition: pos})
        .animate(
          {top : '-100px'},    // Animate until top is 100px above top of screen
          animationspeed, // At this rate
          function() {
            $(this).remove(); // When done, remove the balloon
          }
        )

Open in new window


8. Add the new balloon to the container
  $('body')
    .append( 
      $('<div/>')
        .addClass('balloon')
        .css({top: startheight + 'px', left: leftspace + 'px', backgroundPosition: pos})
        .animate(
          {top : '-100px'}, 
          animationspeed,
          function() {
            $(this).remove();
          }
        )
    );

Open in new window

9. Schedule the next balloon creation.
  setTimeout('balloon()', timeout);

Open in new window


You will notice in the code above there are some parameters we need to define. Specifically, some global variables to hold screen width and height
  // WE ADD 100 TO START BALLOON BELOW THE SCREEN
  startheight = $(window).height() + 100;

  // WIDTH OF THE SCREEN SO WE KNOW WHERE TO POSITION
  // THE BALLOON. WE SUBTRACT THE 100 SO THAT THE BALLOON
  // LEFT POSITION IS NOT THE WIDTH OF THE SCREEN AND
  // THEREFORE OF RIGHT EDGE.
  startwidth = $(window).width() - 100;

Open in new window

We then need some variables that are created for each new ballloon.
  // TIMEOUT BETWEEN CREATING BALLOONS
  // OUR CREATION WINDOW IS BETWEEN 250ms 
  // AND 750ms
  var timeout = randomMinMax(250,750);

  // ANIMATIONSPEED - HOW FAST WE WANT THE BALLOON
  // TO RISE. THE SMALLER THE VALUE THE QUICKER THE
  // ASCENT. HERE WE WANT VALUES BETWEEN 2.5s AND 10s
  var animationspeed = randomMinMax(2500,10000);

  // WHERE TO PUT THE BALLOON ON THE SCREEN RELATIVE
  // TO THE LEFT MARGIN OF THE SCREEN. WE START AT 100
  // FOR THE SAME REASON WE SUBTRACT 100 FROM THE 
  // STARTWIDTH VARIABLE (SEE ABOVE)
  var leftspace = randomMinMax(100, startwidth);

  // WHICH SPRITE TO USE. THIS IS A BACKGROUND-POSITION
  // STRING TO MOVE THE SPRITE IMAGE UP TO THE REQUIRED
  // BALLOON POSITION.
  var pos = '0px -' + (randomMinMax(0,4) * 100) + 'px';

Open in new window


Before we put it all together there is one final function we need to define. randomMinMax. This function returns a random number within a min/max interval
function randomMinMax(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

Open in new window


That's pretty much it. Jquery will handle the rest.

The animation function will run asynchronously on the JQuery object (in this case the newly created balloon div) and when it completes it removes the balloon.

The setTimeout call at the end of the balloon() function sets a random timeout to the next balloon creation process. With the random start time, animation time, balloon colour and position we have a fairly dynamic effect of balloons rising up the back of the page.

Full code listing
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
var startheight = 0;
var startwidth = 0;
$(function() {
  startheight = $(window).height() + 100;
  startwidth = $(window).width() - 100;
  balloon();
});

function randomMinMax(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}

function balloon()
{
  var timeout = randomMinMax(250,750);
  var animationspeed = randomMinMax(2500,10000);
  var leftspace = randomMinMax(100, startwidth);
  var pos = '0px -' + (randomMinMax(0,4) * 100) + 'px';
  $('body')
    .append( 
      $('<div/>')
        .addClass('balloon')
        .css({top: startheight + 'px', left: leftspace + 'px', backgroundPosition: pos})
        .animate(
          {top : '-100px'}, 
          animationspeed,
          function() {
            $(this).remove();
          }
        )
    );
  
  setTimeout('balloon()', timeout);
}

</script>
<style type="text/css">
body, html {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
div.balloon {
  width: 75px;
  height: 100px;
  background-image: url(images/balloons.png);
  background-position: 0 0;
  background-repeat: no-repeat;
  position: absolute;
  top: -9999px;
  left: 90px;
}
</style>
</head>
<body>
</body>
</html>

Open in new window


That's all there is two it. With one line of chained JQuery we have a simple animation of dynamically created objects of different colours starting at random locations and rising at random rates to the top of the screen.
5
Comment
  • 2
2 Comments
 

Administrative Comment

by:lherrou
JulianH,

Congratulations. The Experts Exchange editors have designated your article as Experts Exchange Approved in recognition of the excellence of your article.
0
 

Administrative Comment

by:lherrou
Julian,

When the Editors agree, we can also award the coveted Editor's Choice designation, which recognizes the very top articles at Experts Exchange.

CONGRATULATIONS AGAIN!

I look forward to seeing more excellent work from you.

LHerrou
Experts Exchange Editor
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Join & Write a Comment

The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month