jQuery 1.4: Managing Animations

Exclusive offer: get 50% off this eBook here
jQuery 1.4 Animation Techniques: Beginners Guide

jQuery 1.4 Animation Techniques: Beginners Guide — Save 50%

This book and eBook will enable you to quickly master all of jQuery’s animation methods and build a toolkit of ready-to-use animations using jQuery 1.4.

$23.99    $12.00
by Dan Wellman | March 2011 | Open Source Web Development

jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML, and is the most popular JavaScript library in use today. Using the features offered by jQuery, developers are able to create dynamic web pages.

The techniques that we'll learn in this article by Dan Wellman, author of jQuery 1.4 Animation Techniques: Beginners Guide, include:

  • Viewing the items in an element's queue
  • Counting the items in an element's queue
  • Preventing queued effects from executing
  • Delaying the start of the next effect in the queue
  • Replacing the existing queue with a new queue
  • Calling the next function in a custom queue
  • Stopping the current effect without executing the rest of the queue
  • Globally disabling all animations
  • Changing the frame rate of animations globally

 

jQuery 1.4 Animation Techniques: Beginners Guide

jQuery 1.4 Animation Techniques: Beginners Guide

Quickly master all of jQuery’s animation methods and build a toolkit of ready-to-use animations using jQuery 1.4

        Read more about this book      

(For more resources on this subject, see here.)

The jQuery object itself also contains several properties that can be useful when working with animations. These include:

  • jQuery.fx.off
  • jQuery.fx.interval

The queue is not restricted to storing animation methods; other methods can also be added to the queue. We will only be looking at the queue() method from an animation perspective here.

Working with the queue

When several effects are chained together, the first effect is begun straight away. The remaining effects are stored as functions in an array in the element's fx queue. As the effects are stored in an array, we can call standard JavaScript array methods on it to manipulate it, and examine its properties to find out additional information about it.

We can determine how many functions are in the queue by looking at the length property of the array, or we can call standard functions such as push(), pop(), or reverse() on it to perform various operations on the items (functions) in the array. It is unlikely that this would be required in most normal situations however.

An important point to note about the queue is that the first effect method called on an element does not get stored in the queue, so the length of the queue at the start of the operation will always be one less than the total number of effect methods called on the element.

The queue executes on a first-in-first-out basis, with the last function stored in the queue executing last. The default fx queue for an animated element will run automatically and each function contained within it will be called automatically by jQuery. The string inprogress is used as the first item in the default fx queue as a flag indicating that the queue is currently being run.

A custom queue that we create ourselves will not run automatically and we must ensure that each item in the queue is executed one after the other. jQuery provides several ways of doing this including the dequeue() method, which executes the next function in the queue, and a callback function that we can pass into functions in the queue. We'll look at both of these techniques later in the article.

Viewing the queue

To view the queue we simply call the queue() method; no arguments are required but we can optionally supply the queue name if it differs from the default fx. When the method is called, it returns an array containing the remaining functions in the queue. The queue() method may be used in the following form:

jQuery(elements).queue([queue name], [new queue], [callback]);

In addition to the name of the queue, we can also supply either a new queue, or a single callback function. The new queue, if supplied, should take the form of an array of functions. The new queue will replace the existing queue entirely. Passing an empty array to the queue() method will clear the queue. A callback passed to the queue() method will be added to the end of the queue and executed last after the functions originally in the queue.

A common use of the queue() method is to look at the length property of the returned array to determine how many functions are left to run; but if we need to, we can also look at each function individually by calling the toString() JavaScript function on any item in the array (except for item 0 which will simply display the string inprogress).

Most functions in the returned array are function literals, however, the "next" item in the queue is not available via the queue() method. The contents of item 0 in the default fx queue will always be the string inprogress as this is the animation currently being run.

Time for action - viewing the queue

Let's look at a basic example of the use of the queue() method and the type of results we can expect to obtain.

  1. In the <head> of our template file add the following code:

    <style>
    #fader { width:100px; height:100px; background-color:#000; }
    </style>

  2. Finally, in the anonymous function at the bottom of the second <script> element, add the following code:

    $("#fader").fadeOut(function() {

    console.log($(this).queue());

    }).fadeIn().fadeOut().fadeIn();

  3. Save the page as queue.html.

What just happened?

Typically, we'd use an external stylesheet for any styling, but for a single selector and three rules, it seems pointless creating a separate file. In the script we have four effects chained together to form a simple animation in which our <div> element is simply faded out and back in twice. We provide a callback function as an argument to the first of our effect methods, within which we call the queue() method.

You'll need to use a browser that has a console for this example, such as Firefox. Here's what the output looks like in Firebug:

jQuery 1.4: Managing Animations

In the previous screenshot, we can see that the array making up the queue has been output to the console for us to view. There are three items left in the queue when the method is called. The first item in the array is the string inprogress. The remaining two items are the queued methods that have not yet run.

If we wish to see how many functions are left in the queue (including the one that is in progress), we could change the console.log line to this:

console.log($(this).queue().length);

This code would show the following output in Firebug's console:

jQuery 1.4: Managing Animations

This time our console shows numerically how many items are left in the queue, as shown in the previous screenshot.

We can use other array methods on the queue if we wish (although this would rarely be useful), such as push() or pop() to add or remove items for example. We can also get a single item from the queue if we wish, by adding square braces and an index number after the call to queue():

console.log($(this).queue()[1]);

jQuery 1.4: Managing Animations

As shown above, this time the value of the second item is output to the console. As I mentioned earlier, we can see the actual contents of the function using the toString() JavaScript function:

console.log($(this).queue()[1].toString);

Running this code produces the following output:

(Move the mouse over the image to enlarge it.)

The code shown in the previous screenshot won't make much sense to the casual observer as it's been minified, but it's the contents of jQuery's fadeout() method.

Adding a function to the queue

Appending a new function to the end of the queue is a trivial matter and we don't even need to use a new method. We just need to pass the new function, or a function reference, to the queue() method as an argument.

When we pass a single function into the queue() method and we are working with the default fx queue, jQuery will automatically call the function for us using the dequeue() method. We haven't looked at the dequeue() method yet, but we will cover this a little later in the article.

jQuery 1.4 Animation Techniques: Beginners Guide This book and eBook will enable you to quickly master all of jQuery’s animation methods and build a toolkit of ready-to-use animations using jQuery 1.4.
Published: March 2011
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources on this subject, see here.)

Time for action – adding a single function to the queue

Let's see how easy it is to add a new function to the end of the queue.

  1. Update the script in queue.html so that it appears as follows:

    $("#fader").fadeOut(function() {

    $(this).queue(function() {
    $(this).css("backgroundColor", "green");
    });

    }).fadeIn().fadeOut().fadeIn();

  2. Save the new file as queueAdd.html.

What just happened?

By supplying a callback function as the optional second argument to the queue() method, we add the function to the end of the animation queue. When we run the code in a browser the animation should proceed as normal; then once the effects have run, the <div> will turn green.

We don't need to supply the name of the queue unless it differs from the default fx queue. In this simple example, we just change the background-color of the target element, but in reality a function of any complexity can be appended to the queue.

jQuery handles calling this function for us when we add it to the default fx queue. When working with custom queues we will need to dequeue the function manually using the dequeue() method, which we'll look at shortly.

Using a callback function to keep the queue moving

In the last example, the function that we added to the queue was added as the last function in the queue, so ensuring that the queue kept running was not necessary. Sometimes however we may need to add several functions to the end of the queue, and will therefore need to execute the additional functions ourselves.

Time for action – keeping the queue running

  1. Change the <script> element at the bottom of the queueAdd.html so that it appears as follows (new code is shown in bold):

    $("#fader").fadeOut(function() {

    $(this).queue(function(next) {
    $(this).css("backgroundColor", "green");
    next();
    }).fadeOut();

    }).fadeIn().fadeOut().fadeIn();

  2. Save this file as queueInsert.html.

What just happened?

This time we have chained an extra call to the fadeout() method to the end of the queue() method inside the callback function for the first fadeout() method. We still pass an anonymous function to the queue() method, but this time we supply an argument to this function as well.

The argument we supply to the function passed into the queue() method is called next. jQuery will treat whatever we pass in as a function and all we have to do is call this function from within the callback function and that will make sure the next function in the queue is executed.

The function we pass into the callback function passed to the queue() method doesn't have to be identified as next, it can be any accepted function name. In this example, we call the next function after setting the background-color of the <div> to green.

This will cause the extra fadeout() method to be executed last, so when we run this example in a browser, we should find that the green <div> disappears at the end.

Replacing the queue

Sometimes adding a single function to the end of the queue may not be enough—we may wish to replace the queue entirely. This behavior is also managed entirely by the queue() method.

Time for action – replacing the queue

  1. We'll update the queue.html file once again for this example. We'll need another style rule in the <style> element in the <head> of the page:

    #fader span {
    display:none; width:100%; height:100%; position:absolute;
    left:0;
    top:0;
    }

  2. We should also add position:relative; to the #fader selector.
  3. Now change the script at the bottom of the page to this:

    <script>
    (function($){

    function changeColor(element, newColor) {

    $("<span>").css("backgroundColor",
    newColor).appendTo(element).fadeIn(500, function(){

    element.dequeue();

    });
    }

    var fader = $("#fader");

    var newQ = [

    function() { changeColor(fader, "yellow") },
    function() { changeColor(fader, "orange") },
    function() { changeColor(fader, "green") },
    function() { changeColor(fader, "red") },
    function() { changeColor(fader, "blue") },
    function() { changeColor(fader, "purple") }
    ];

    $("#fader").fadeOut(function() {

    //replace queue
    $(this).queue(newQ);

    }).fadeIn().fadeOut().fadeIn();

    })(jQuery);
    </script>

  4. Save the file as queueReplace.html.

What just happened?

First we define a single function which accepts two arguments. The first is a jQuery object referring to the animated element and the second is a new color.

We then create a new <span> element, set its background-color to the color passed into the function, append it to the element passed in to the function, and then fade it into view.

We pass a callback function into the fadeIn() method used with the new <span>. In this function, we just call the dequeue() method. This is required for the next function in the queue to be executed; if we don't do this, only the first function in our custom queue will be executed.

Next we define our replacement queue, after first caching a selector for the #fader element. The new queue is defined as an array where each item consists of an anonymous function which in turn invokes our colorChange() function, passing in the cached selector and a CSS color name.

Finally, we call an effect method on the target element and queue up some additional effects as we did before. This time when we call the queue() method, we supply our custom queue, which replaces the default fx queue created by the chained fade methods.

When we run the page in a browser, we see that the first effect is applied, and then our queue of custom colorChange functions is called. The two fade effects that would have been in the default fx queue originally are not executed.

Ensuring custom queues iterate correctly

When we create custom queues, the chained methods are not automatically called for us. This is something we need to do manually and is handled using the dequeue() method as we saw in the previous example.

When called, it will remove the next function in the queue and execute it. It's a simple method, with few arguments, and is used in a very specific manner. The method may take a single optional argument which is the name of the queue to execute the next function from:

jQuery(elements).dequeue([queue name]);

The queue name is only required if we are working with a queue other than the default fx queue. We didn't need to provide the name of the queue in the previous example in the last section because we replaced the animated element's default fx queue. The dequeue() method has the same effect as calling the next() function that we used to keep the queue moving in the queueInsert.html example from the last section.

Time for action – dequeueing functions

Let's change the queueInsert.html page so that it uses the dequeue() method instead of the next() function to keep the queue moving.

  1. Change the code in queueAdd.html so that it appears as follows:

    $("#fader").fadeOut(function() {

    $(this).queue(function() {
    $(this).css("backgroundColor", "green").dequeue();
    }).fadeOut();

    }).fadeIn().fadeOut().fadeIn();

  2. Save this version as dequeue.html.

What just happened?

This time we do not need to pass anything into the callback function passed to the queue() method. We simply chain the dequeue() method to the <div> after setting its background-color to green. This has the same effect as before and the green <div> will fade out at the end of the animation.

Stopping an animation

The stop() method can be used to stop an effect that is currently running on the selected element. In its simplest form, we may call the method without supplying any additional arguments, but if necessary we can supply up to two Boolean arguments. The method takes the following format:

jQuery(elements).stop([clear queue], [jump to end]);

The first argument clears the element's queue and the second forces the final state of the effect to be applied.

The stop() method behaves differently depending on whether there are any additional effects in the fx queue.

When the method is called and there are no functions in the queue, any effects that are currently running on the selected element(s) will simply stop and the element will remain in whatever state it reached during the animation.

If there are several functions in the queue however, the current animation will be stopped in whatever state it is in at the time, but then the remaining functions in the queue will be executed.

Take the following code for example:

$("#fader").fadeOut(5000).fadeIn().fadeOut().fadeIn();

$("#stop").click(function() {
$("#fader").stop();
});

If the stop element is clicked while the first effect is running, the fader element will flicker as the remaining effects are applied one after the other.

To prevent the queued functions being executed, we can supply true as the value of the first argument. To force the element into its final state, we can also supply true as the value of the second argument. Both arguments default to false.

The stop() method can be really useful for preventing animation build-up. If an animation is triggered by clicking a button for example and the button is clicked repeatedly, the animation can run multiple times. Usually this behavior is undesirable and can be prevented using the stop() method.

To see the differences between each variation of the stop() method, see the stopTest.html file in the accompanying code download.

Time for action – preventing animation build-up using the stop method

As seen in the following navigation menu example, we use the fadeIn() method to enhance CSS hover states, but we don't hide the hover state using fadeOut().

ul.find("a").hover(function() {
$(this).find("span").fadeIn("slow");
}, function() {
$(this).find("span").hide();
});

The reason for this is because the animations can quickly build up. If the mouse pointer is moved on and off one of the links repeatedly, the hover state will continue to fade in and out even after the mouse pointer moves away.

Fortunately, we can use the stop() method to prevent this from happening. In this section, we'll add fadeOut() effects to the navigation menu example as shown in the above code and use the stop() method to prevent an effect build-up.

  1. In fadeIn.html, change the hover() method so that it appears as follows:

    ul.find("a").hover(function() {
    $(this).find("span").stop(true, true).fadeIn("slow");
    }, function() {
    $(this).find("span").stop(true, true).fadeOut("slow");
    });

  2. Save this file as stop.html.

What just happened?

By calling the stop() method directly before applying the fadeIn() effect, we ensure that a build-up of effects does not occur and spoil the hover states. In order for the effects to work correctly, we supply true as the values of both the clear queue and jump to end arguments.

Delaying queue execution

As of jQuery 1.4 we can choose to delay the execution of the next function in the queue using the delay() method. We need to supply the duration as an argument to the method to tell it how long the delay before the next effect starts should be, and we can optionally supply the name of the queue to delay as an argument as well. The method is used in this format:

jQuery(elements).delay(duration, [queue name]);

The duration argument may be supplied as an integer representing the length of the duration in milliseconds, just like the effect methods we've covered so far, or it may be one of the strings slow or fast which correspond to the standard values. If no duration is provided, the queue will not be delayed, and if a string other than slow or fast is provided, the delay will be the default duration of 400 milliseconds.

The queue does not need to be directly manipulated in order to set a delay. All we need to do is chain the method between our animation methods, so an animation that fades an element in and out several times that required a delay could be constructed like this:

$("#fader").fadeOut().delay(2000).fadeIn().fadeOut().fadeIn();

Note that the delay() method is only supposed to be used with methods or functions in a queue, just like the stop() method, and cannot (and is not meant to) replace JavaScript's setTimeout() function.

Plugins There are several great plugins that make working with both the setTimeout() and setInterval() native JavaScript functions quicker and easier. Just search the plugin repository for setTimeout.

Clearing the queue

As well as viewing the queue and manipulating its contents, we can also remove all of the functions from it entirely. jQuery provides the clearQueue() method allowing us to easily clear all functions in the specified element's queue.

Like dequeue(), this is a simple method that takes just a single optional argument:

jQuery(elements).clearQueue([queue name]);

This method is generally used with non-animation-based queues, when using the stop() method is not possible, and so will not be discussed further.

Passing an empty array to the queue() method will also clear the queue.

Useful properties of the jQuery object

The jQuery object contains a couple of properties that we can set which can be useful when creating animations. The jQuery (or $) object contains an fx property, which itself contains two properties related to animations which we can manipulate.

This fx object is not to be confused with the fx queues that are created by default for any element that has more than one animation method called on it in a chain. These individual fx queues do not contain the same properties that the jQuery fx property contains.

Globally disabling animations

One property of fx that we can set is the off property. This property contains a Boolean that is set to false by default, but which we can set to true to globally disable all animations on a page. The property is set using the following syntax:

jQuery.fx.off = true;

That's all we do need to do. If this is set at any point in our script, all elements that have animation methods attached to them will be set to their final state, as if the animation had already completed.

Changing the default frame rate

The other property of jQuery's fx that we can set is the interval property. This property accepts an integer and specifies the number of milliseconds between each frame of the animation. By default, it is set to 13, so an animation will have a frame-rate of about 76 frames per second.

To set this property, we just supply a different integer:

jQuery.fx.interval = 28

Setting the property to 28 like this would make the animation run at about 35 frames per second, making animations run almost half as smoothly.

Note that animations will still run over the same duration of time (whether that is the default 400 milliseconds, or another value set with the duration argument of an animation method) regardless of what this property is set to. However, an interval value that is lower, and therefore has a higher number of frames per second, will make animations appear smoother.

Also note that the lower we set the interval property, the more intensive animations will be. While the latest browsers will cope with these increased demands satisfactorily, older or slower browsers will struggle.

There must be no animations running when this property is set for it to take effect. Any animations that are running must be stopped.

Summary

This article covered the animation queue and the methods jQuery provides for managing it. We saw how to clear the queue, how to add functions to it, and how to clear it. We also saw how to add a delay between queued items and how to prevent animations building up in the queue when they are not required.


Further resources on this subject:

jQuery 1.4 Animation Techniques: Beginners Guide This book and eBook will enable you to quickly master all of jQuery’s animation methods and build a toolkit of ready-to-use animations using jQuery 1.4.
Published: March 2011
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Dan Wellman

Dan Wellman is an author and frontend engineer living on the South Coast of the UK and working in London. By day he works for Skype and has a blast writing application-grade JavaScript. By night he writes books and tutorials focused mainly on frontend web development. He is also a staff writer for the Tuts+ arm of the Envato network, and occasionally writes for .Net magazine. He's the proud father of four amazing children, and the grateful husband of a wonderful wife.

Books From Packt


Django JavaScript Integration: AJAX and jQuery
Django JavaScript Integration: AJAX and jQuery

jQuery Plugin Development Beginner's Guide
jQuery Plugin Development Beginner's Guide

PHP jQuery Cookbook
PHP jQuery Cookbook

CMS Design Using PHP and jQuery
CMS Design Using PHP and jQuery

WordPress 3.0 jQuery
WordPress 3.0 jQuery

Joomla! 1.5 JavaScript jQuery
Joomla! 1.5 JavaScript jQuery

jQuery UI 1.7: The User Interface Library for jQuery
jQuery UI 1.7: The User Interface Library for jQuery

Python 2.6 Graphics Cookbook
Python 2.6 Graphics Cookbook


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
s
h
W
A
5
4
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software