jQuery Methods for Creating Advanced Animation
 
 

 You can use these jQuery methods with div containers and images, but there are times when you want to create more custom animations than the standard set of methods offer. JQuery has several methods for custom animations, easing functions, scheduling and cancelling procedures, and disabling animations. This article covers these four aspects of advanced animations.

Custom Animations

When you can't use the "out of the box" jQuery methods, you can use several of the methods jQuery offers for custom animations.

The basic and most common custom animation method is the "animate" method. This method gives you much more customization options when you want to animate an image or other element. The animation options are based on CSS properties, so you can either set up your own animation classes or use basic properties for the method's parameters.

Let's first take a look at the basic use for the animate method. First, we need a div container with initial properties.

<button id="button1">Increase div height</button>

<div id="main" style="background-color: green;height:100px;width:100px;"></div>

This div container is a small 100x100 box on the screen with a green background. We can use the animate method to change the properties of this div container.

The following jQuery code uses the animate method to change the container's height after the user clicks the button.

<script>

$("#button1").click(function(){

        $("#main").animate({height: "400px"});

</script>

Notice that we only have one CSS property listed in the animate method. You can use several property methods. Just note that these properties must be contained within the open and close brackets ( '{' and '}').

The following code adds an additional property to the animation.

<script>

$("#button1").click(function(){

        $("#main").animate({height: "400px", width: "300px"});

</script>

Now the animation changes the div container's width and height when the button is clicked.

You can get much more specific with the animate method. You can animate elements, set a duration, configure easing and define what happens after the animation is complete. The following code adds a few more parameters to the above animate method to define more options for your animation.

<script>

$("#button1").click(function(){

        $("#main").animate({height: "400px", width: "300px"},

            , {

      duration: 3000,

      easing: "linear",

      complete: function(){

        $(this).after("<p>The animation finished.</p>");

      });

</script>

We kept the same animation CSS properties, but we added a duration, easing configuration and final function. The duration setting is configured in milliseconds. This means that the animation takes 3000 milliseconds (3 seconds) to animate.

The second property is easing. Easing determines the pace at which the animation happens. With "linear," the 3000 milliseconds are spanned equally across the entire animation time. With "swing" (the default), animation starts slow and increases speed in the middle of the timing, and then it slows down at the end of the animation time. You can review both settings side-by-side when you create your animations to review which one is better for your web page.

The "complete" parameter tells jQuery what to do after the animation is finished. In this example, a paragraph is added to the end of the animated div that contains the text "The animation finished." You can perform any number of functions in this section including calling another function.

While the animate method is the most common when working with custom animation, jQuery offers several other functions. Another such function you can use is the delay method. The delay method lets you use the standard methods we worked with in the previous section. You can use the delay method to delay activity of the next animation. Take a look at the following code to see how it works.

<script>

$( "#main" ).slideUp( 400 ).delay( 1000 ).fadeOut( 500 );

</script>

In the above script, we first used the slidUp method on the main div container. We then wait for 1000 milliseconds (1 second), and then use the fadeOut method to make the container transparent.

You don't need to wait for an animation to finish. You can prematurely stop the animation using the "finish" method. The finish method is simple to run. The following code shows you how to stop the animation on the main div container.

$("#button1").click(function(){

    $("#main").finish();

});

In this example, the animation is started when the user clicks the button, but it's immediately finished. Note that calling the finish method jumps to the end of the animation, so it's finished and complete.

The final custom animation method to know is the "stop" method. The finish method completes the animation immediately. The stop method puts a full stop on the current animation without finishing it. It's used in the same way that the finish method is used. The following code is an example.

$("#button1").click(function(){

    $("#main").stop();

});

In the above example, the animation starts and then stops, which means that you only see a short start to the animation before it's immediately stopped.

Easing Functions

We mentioned easing options in the previous section. There are two main easing functions called "linear" and "swing." We mentioned that linear spreads the animation steps equally between each millisecond. The swing option causes the animation to start off slowly, speed up in the middle, and then slow down again. The default value for the animation method is the swing option.

Although we covered only two easing options, there are several more offered by the jQuery API. The line graphs represent the way an animation is shown when the user sees it. You can have an animation start when the user opens the page or when an event happens such as a button click.

As you can see from the web page, there are a couple dozen options for easing functionality. The best way to identify which one is right for you is to use a tool to view your animation for each easing option. Most developers use the simple linear or swing easing option, but you may have more complex animations that require the additional configurations.

You can use easing in either your CSS code or jQuery and JavaScript. The curve you see for each easing option is called the Bezier curve. You must specify this curve for both jQuery and CSS. We'll show you how to use this curve in both languages.

Let's first take a look at what the animation easing function looks like in CSS. Once you see it in CSS, it's easier to understand in jQuery.

The following code is an example of using animations easing configurations in CSS for a div container.

div {

 transition:         all 800ms easeInQuint; }

In the above code, we used the "easeInQuint" easing option. Remember that CSS must cover all main browsers and these browsers support different syntax. The webkit prefix indicates that you want to support Chrome, Safari and Opera. The second one is for Internet Explorer.  We specified that the animation should take 800 milliseconds. If you take a look at the easing cheat sheet, you'll notice that this option specifies a slow initial animation process and then it speeds up considerably.

Now it's time for the jQuery syntax. As with other animation methods, jQuery uses a method to indicate the options for your animation. If you recall, we mentioned that the animate method is used for most custom animations, and this includes ones with custom easing configurations.

Take a look at the following jQuery code that implements a custom easing function.

$("#main").animate({height: 300}, 3000, "easeInQuint");

Notice that the animate method looks the same as it did in the previous section. We've linked it to the main div container we created in the previous section. We set a height with an animation time of 3000 milliseconds (3 seconds). We then specify the easeInQuint easing configuration. It's the same as what we set in CSS, so the results are the same only this method is only executed when you call the jQuery code.

Queue Scheduling and Cancelling

When you create an animation, you have queued items for each step. You can control the queue using a few methods. The "queue" method can be used to display the number of queued items that will run. You can also use the dequeue method that removes any following methods from the queue. If you want to completely remove any of the next items in the queue, you use the clearQueue method. This section will show you how to use all three methods.

First, let's cover the queue method. It's used to show you the number of actions left in the animations. For instance, suppose you have four animation elements in your jQuery code. The following function shows all four of them that will execute when it's called.

function animate() {

 div

    .show( "slow" )

    .animate({ background-color: black;" }, 2000 )

    .slideToggle( "fast" )

    .hide( "slow" )

}

We have four animation methods on a div container in the above code. It's set within a function, so these methods are only called when the function is called.

The animations are basic. First, the div container is shown. Then, its background is animated to black. Then the slide toggle is called to slide it up or down. Finally, the div container is hidden.

Each of these animation calls increases the jQuery animation queue number. By default, jQuery uses the "fx" queue name, but you can specify a queue name if you prefer to rename it.

You can get the number of elements in a queue using the "length" property. The following code shows you how to display the length of the queue in a paragraph located on the page.

var queue = div.queue( "fx" );

 $( "p" ).text( queue.length );

The above code first references the default fx queue to a variable named queue. The length property is then called on the variable to get the length of the queue. Each time one of the animation methods is executed, the queue length is reduced by one. You can use the length property to identify the number of animation steps left in a procedure. If the queue length reaches a certain number, you can then stop the animation prematurely.

When you want to remove the next method from executing, you can do so using the dequeue method. The dequeue method removes a function but then executes it. The following code is how you use the dequeue method.

$('main').dequeue();

That's it. This method is usually implemented when you want to interrupt the animation for some reason such as a change in animation properties or when you want to change its behavior.

The final queuing mechanism that you need to know is the "clearQueue" method. This method is similar to the stop method. It removes all future items in the queue that have not yet run. It does not reset the element to the beginning of the animation queue. It only removes items that have not run.

The following code shows you how to clear the animation queue.

$('main'). clearQueue ();

The clearQueue method is called in the same way as the other methods. Just remember that once this method is called, no other animation items are executed, so the animation stops abruptly.

Once you understand the way the animation queue works, the next step is enabling and disabling animations.

Disabling Animations

Disabling animations doesn't completely stop it. When you disable animations, you remove the effects. Take our animation with the div element. You noticed that there was a changing effect that happened as the animation moved from one div size to another. When you disable animations, you no longer see that slow, timed effect. The animation part is removed and only the first and last effect is shown.

For instance, if you have a div animation where the container goes from a 100 pixels in height to 200 pixels, removing the animation would show only the initial div size and then the ending size with no smooth processing frames in between.

We can use the methods on the div we created in the previous section.

<button id="button1">Increase div height</button>

<div id="main" style="background-color: green;height:100px;width:100px;"></div>

With the element created, you can now create your animation code. We'll perform a simple toggle of visible to hidden. The following jQuery code toggles the visibility for the above div container.

$("#button1").click(function(){

        $("#main").toggle("slow");

    });

With simple animation, the change happens slowly. You slowly see the div container change from visible to invisible.

By disabling animation, you can make the change abruptly. The following code shows you how to disable the animation.

$("#button1").click(function(){

       jQuery.fx.off = true;

        $("#main").toggle("slow");

    });

In the code above, the jQuery "fx" are turned off. The "off" property can be set to true or false. When you set it to true, the animation effects are turned off. If you set the property to false, the animation effects are flipped on. That's all it takes to turn your animation effects on and off.

It takes time to get used to the different animation effects with jQuery especially since you need to implement CSS along with your JavaScript code. You will need to experiment in your applications to find the right effect that works for you. You can use your own custom tools to view different effects or use different animation style settings to figure out which one works the best for your web pages.