jQuery - Custom Queue

jquery

What is jQuery queuing mechanism used for?

jQuery has a built-in queuing mechanism that's used by all of its animation methods (all of which use 'animate()' really). This queuing can be illustrated easily with a simple animation:

jQuery('a').hover(function(){
    jQuery(this).animate({<wbr>paddingLeft:'+=15px'});
}, function(){
    jQuery(this).animate({<wbr>paddingLeft:'-=15px'});
});

Quickly hovering over a bunch of anchors and then hovering over them again will cause the animations to queue up and occur one at a time.

How does the queue() method work?

The 'queue' method is similar to the well-known 'each' method in how it's called. You pass a function, which will eventually be called for each of the elements in the collection:

jQuery('a').queue(function(){
    jQuery(this).addClass('all-done').dequeue();
});

Passing just a function to 'queue' will cause that function to be added to the default 'fx' queue, i.e. the queue used by all animations done by jQuery. Therefore, this function will not be called until all current animations occurring on each element in the collection (in this case, all anchors) have completed.

What is the name of the default queue that is used for animation?

fx. Passing just a function to 'queue' will cause that function to be added to the default 'fx' queue, i.e. the queue used by all animations done by jQuery.

Why should we remember to call dequeue function?

This is very important, as it will allow jQuery to continue with the queue (i.e. it lets jQuery know that you're finished with whatever you're doing). jQuery 1.4 provides another way of continuing the queue; instead of calling 'dequeue', simply call the first argument passed to your function:

jQuery('a').queue(function(nextItemInQueue){
    // Continue queue:
    nextItemInQueue();
});

This does exactly the same, although it's slightly more useful in that it can be called anywhere within your function, even within a mess of closures (that typically destroy the 'this' keyword). Of course, pre-jQuery-1.4 you could just save a reference to 'this', but that would get a bit tiresome.

How can we add a function to a custom queue?

To add a function to a custom queue, simply pass your custom queue's name as the first argument and the function as the second:

jQuery('a').queue('customQueueName', function(){
    // Do stuff
    jQuery(this).dequeue('customQueueName');
});

Notice that, since we're not using the default 'fx' queue, we also have to pass our queue's name to the 'dequeue' method, in order to allow jQuery to continue with our custom queue.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License