Web Development optimize

How to create animations with jQuery

Ryan Boudreaux illustrates a simple animation effect in jQuery.
Continuing in our tutorial series of introducing jQuery functions and features, we will demonstrate creating an animation using the .animate() function. All files used in the demonstration section of this tutorial are available for download so you can follow along.

The jQuery library provides several methods for including animation on web document pages. These include simple, standard animations that are frequently used and also the ability to craft sophisticated custom effects. In this segment, we'll closely inspect several of the effect methods, revealing the power jQuery has for providing visual feedback to the visitor.

If you have missed the otherfive parts of the jQuery series, be sure to check them out below, as they set the foundation for the continuation of steps we will take in this segment:

Let's get animated with the .animate() function

The jQuery .animate() function performs a custom animation of a set of CSS properties. Functions include Duration, Easing, and Complete

Other options include Step, where there is a function to be called after each step of the animation; Queue, where a Boolean is used to indicate whether to place the animation in the effects queue( a false statement will begin the animation immediately); and SpecialEasing, where a map of one or more of the CSS properties is defined by the properties argument and the corresponding easing functions are specified.

The syntax is expressed in this form:

.animate( properties [, duration] [, easing] [, complete] )

  • Properties: A map of CSS properties that the animation will move toward.
  • Duration: A string or number determining how long the animation will run.
  • Easing: A string indicating which easing function to use for the transition.
  • Complete: A function to call once the animation is complete.

The .animate() method allows the creation of animation effects on any numeric CSS property; the only required parameter is a map of CSS properties, similar to the one that can be sent using the .css() method, except that the range of properties is more restrictive.

Properties and values

Animations should always be set to a single numeric value, unless otherwise noted, since most properties that are non-numeric cannot be animated unless using basic functionality such as width, height, and left. Background-color cannot be animated unless the jQuery.Color () plug-in is utilized. Property values are treated as pixels expressed numerically, and units in em and % can be specified where they apply. In addition, some non-style properties such as scrollTop, scrollLeft, and some custom properties can also be animated. Shorthand CSS properties are not fully supported.

Durations

Durations are given in milliseconds where higher values indicate slower animations, and the default duration is 400 milliseconds. Duration of 600 milliseconds is interchangeable with a ‘slow' setting, and duration of 200 milliseconds is interchangeable with a ‘fast' duration setting.

Complete function

The complete function is fired once the animation is completed, and this is useful when we want to string different animations together in a sequence.

Our first basic animation

So, let's get started with building an animated object and we will start with a new clean HTML document, in the download that would be found in the web directory and it is the index.html file. We also have an associated CSS stylesheet (styles.css) and the jQuery script file (jquery.js) located in the scripts directory.

Our basic HTML code starts with this snippet (see index.html file in download):

<!DOCTYPE html>
<html lang="en">
 <head>
    <meta charset="utf-8">
    <title>jQuery Tutorial</title>

   <link rel="stylesheet" href="styles.css" type="text/css" media="screen" />
 </head>
 <body>
   <!-- HTML -->

     <section>

       <article id="animate_01">
         <p>Animate the rose!</p>
       </article>

       <img id="rose" class="image_01" src="images/Rose.gif" alt="Rose" title="Rose" width="400" height="294" />

     </section>

We will use the rose image from the download with an id="rose", class="image_01" with the defined height and width inside the <img> tag.

In our styles.css file we will add in the following style definitions:

.image_01 {
       position: relative;
       left: 10px;
}

#animate_01 {
       cursor: pointer;
       border-color:#CCC;
       border:solid thin;
       width:125px;
       margin:5px;
       padding:5px;
       text-align:center;

}

#complete {
       text-decoration:underline;
       font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
       margin:10px;
       padding:10px;
       color:#339;

}

article p {
       font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
       font-size:14px;
}

And, for our jQuery, we will add in the following snippet to our document ready function which starts with the // Animate the image comment for the animation code; here we set the opacity to 0.35, a left offset to ‘+=100', and the height toggles simultaneously: (Note: the call to the jquery.js file and the <script> with the $(document).ready(function()).

   <!-- Scripts -->
   <script src="scripts/jquery.js"></script>

   <script>
    // JavaScript

      $(document).ready(function(){
               // Your code here

        // Animate the image
        $('#animate_01').click(function() {
          $('#rose').animate({
          opacity: 0.35,
          left: '+=100',
          height: 'toggle'
          }, 5000, function() {
        // Animation complete statement
        $(this).after('<article id="complete">Animation is now complete!</article>');
        });
       });
      });

   </script>

The image was visible before the animation, so once the animation is triggered, it shrinks the height to 0 to hide it, as displayed below in Chrome 18.0.1.

Figure A

A second click then reverses this transition, but the opacity remains, and since the target value for left is a relative, the image shifts even farther to the right during each successive animation as displayed in Figure B where the "Animate the rose!" button was clicked twice -- once to hide and then once to show (Note: The "Animation is now complete!" shows each time the animation is completed:

Figure B

In future jQuery posts, I will review more animation functions such as .fadeout(), and .slideToggle().

About

Ryan has performed in a broad range of technology support roles for electric-generation utilities, including nuclear power plants, and for the telecommunications industry. He has worked in web development for the restaurant industry and the Federal g...

2 comments
lehnerus2000
lehnerus2000

I have to create an xml webpage for one of my networking course subjects. I might be able to earn a few bonus points by applying your tutorial. :)

RJBoudreaux
RJBoudreaux

Bonus points are always a nice thing! Good luck with the course!