Every element can have one to many queues of functions attached to it by jQuery. In most applications, only one queue (called fx
) is used. Queues allow a sequence of actions to be called on an element asynchronously, without halting program execution. The typical example of this is calling multiple animation methods on an element. For example:
1 | $('#foo').slideUp().fadeIn();
|
When this statement is executed, the element begins its sliding animation immediately, but the fading transition is placed on the fx
queue to be called only once the sliding transition is complete.
The .queue()
method allows us to directly manipulate this queue of functions. Calling .queue()
with a callback is particularly useful; it allows us to place a new function at the end of the queue. The callback function is executed once for each element in the jQuery set.
This feature is similar to providing a callback function with an animation method, but does not require the callback to be given at the time the animation is performed.
1 2 3 4 5 | $('#foo').queue(function() {
alert('Animation complete.');
|
This is equivalent to:
1 2 3 | $('#foo').slideUp(function() {
alert('Animation complete.');
|
Note that when adding a function with .queue()
, we should ensure that .dequeue()
is eventually called so that the next function in line executes.
As of jQuery 1.4, the function that's called is passed another function as the first argument. When called, this automatically dequeues the next item and keeps the queue moving. We use it as follows:
1 2 3 4 | $("#test").queue(function(next) {
|