A Bouncing Ball Animation in jQuery

Out of the box and without plug-ins, you can animate elements with basic jQuery. You can view a live example of the following code which animates the position of a "ball" up and down.

There are a number of overloads for the jQuery animate function, the one used in this example takes 4 parameters:

  1. params: numeric property value(s) you want changed over time as the animation runs;
  2. duration: how long the animation takes ("slow", "normal", "fast", or number of milliseconds);
  3. easing: "linear" or "swing";
  4. callback: a function to be called when the animation finishes.

For example:

$("#ball").animate({ top: "1px" }, "slow", "swing", animDown);

This code changes the top property "slow"ly to a value of 1px whilst creating a non-linear "swing" motion. When the value of top reaches 1px, the animation has completed and the callback function animDown is called.

In the code below, the continuous bouncing is achieved by having 2 separate animation functions defined: animUp and animDown. Once the animUp animation completes it calls the animDown function and vice versa.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <title>Bouncing Ball Animation in jQuery</title>

    <script type="text/javascript" src="jquery-1.3.2.js"></script>

    <script type="text/javascript">

        /* Entry point into the animation 'loop'. Once the the animation is complete
           i.e. the ball is at the top, the animate call the callback function animDown */          
        function animUp() {
            $("#ball").animate({ top: "1px" }, "slow", "swing", animDown);

        /* Called when the up animation completes. Once this downanimation is complete
           i.e. the ball is at the bottom, the animate function calls the callback function
           animUp */
        function animDown() {
            $("#ball").animate({ top: "446px" }, "slow", "swing", animUp);

        $(document).ready(function() {

    <div><h1>Bouncing Ball Animation in jQuery</h1></div>
    <div id="ballContainer" style="width: 500px; height: 500px; display:block;
        background-color: White; border-bottom: solid 10px Black;">
        <div id="ball" style="position: relative; overflow: hidden;
            background-color: Transparent; color: Black; font-size: 50pt;
            top: 450px; left: 225px;">
    <h4>from: <a href="http://www.dontcodetired.com" title="Don't Code Tired">Don't Code Tired</a></h4>


Add comment