How to Add a Function to the jQuery Queue
This article explains how to manually insert custom JavaScript
functions into a jQuery animation queue using the .queue()
method. You will learn the mechanics behind the default
"fx" animation queue, how to properly chain custom logic
alongside native jQuery effects, and how to use the next()
callback to prevent the queue from stalling.
Understanding the jQuery Animation Queue
By default, jQuery executes animation methods like
.slideUp(), .fadeIn(), and
.animate() sequentially on an element using an internal
execution queue named "fx". While standard effects wait for
preceding animations to complete automatically, regular JavaScript code
executes immediately unless it is explicitly attached to the same
queue.
Using the .queue()
Method
To insert a custom function into an element's animation sequence,
call the .queue() method directly within your method
chain.
Syntax
$(selector).queue(function(next) {
// Custom logic here
next();
});The next() Callback
When jQuery executes a function inside a queue, it passes a
next function as the first parameter. Calling
next() signals jQuery to proceed to the subsequent
animation or function in line. If you omit next(), the
queue stalls, and any subsequent animations attached to the element will
never execute.
Implementation Example
Consider an element that needs to animate, change its background color via a custom CSS class, and then animate again:
$("#box")
.animate({ width: "300px" }, 1000)
.queue(function(next) {
$(this).addClass("active");
// Perform any custom asynchronous or synchronous tasks here
next();
})
.animate({ height: "300px" }, 1000);In this sequence:
- The element expands in width over one second.
- The custom queued function executes, applying the
activeclass. next()is called immediately after the class is added.- The element expands in height over the next second.
Using $(this).dequeue()
In older codebases or environments running jQuery versions prior to
1.4, the next argument may not be available. In those
cases, use $(this).dequeue() to advance the execution stack
manually:
$("#box")
.fadeOut(500)
.queue(function() {
// Custom logic
console.log("Animation finished hiding.");
$(this).dequeue();
})
.fadeIn(500);Both patterns achieve the same result, but passing and invoking
next() is the modern and preferred approach.