jQuery Queue

The jQuery queue() method is used to manage a sequence of functions (queue) to be executed on selected elements. It is often used with animations but can be applied to any chain of actions.

Key Topics

Basic Usage of queue()

The queue() method retrieves or sets the queue of functions to be executed on the selected element.

$("#box").queue(function(next) {
    $(this).css("background-color", "yellow");
    next(); // Continue to the next function in the queue
});

Explanation: This code adds a function to the queue that changes the background color of the element with the ID box and then calls next() to continue.

Creating a Custom Queue

You can create and manage your own queue by adding custom functions.

$("#box").queue("customQueue", function(next) {
    $(this).text("Step 1");
    next();
});
$("#box").dequeue("customQueue");

Explanation: This code creates a custom queue named customQueue, adds a function to it, and then executes the queue using dequeue().

Using dequeue()

The dequeue() method executes the next function in the queue. It is often used after completing a task to trigger the next action.

$("#box").dequeue();

Explanation: This code dequeues the next function in the default queue of the selected element.

Example: Using queue()


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Queue Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div id="box" style="width: 200px; height: 100px; background-color: red; color: white; text-align: center; line-height: 100px;">
        Box Content
    </div>
    <button id="startQueue">Start Queue</button>

    <script>
        $(document).ready(function() {
            $("#startQueue").click(function() {
                $("#box")
                    .queue(function(next) {
                        $(this).css("background-color", "yellow");
                        next();
                    })
                    .queue(function(next) {
                        $(this).css("color", "black");
                        next();
                    })
                    .queue(function(next) {
                        $(this).text("Queue Completed");
                        next();
                    });
                $("#box").dequeue();
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example demonstrates how to use the queue() method to chain multiple actions and execute them sequentially on a box element when a button is clicked.

Key Takeaways

  • Action Sequencing: Use queue() to define a sequence of actions to be executed on an element.
  • Custom Queues: Create and manage custom queues for specialized tasks.
  • Chained Execution: Combine queue() and dequeue() to control the execution flow dynamically.