jQuery Callback

A callback function in jQuery is a function that is executed after another function has completed. Callbacks ensure that specific code runs only after a particular task is finished, providing better control over asynchronous operations.

Key Topics

Basic Callback Usage

Callbacks can be added as arguments to methods like hide(), show(), or animate(). The callback function executes after the method completes.

$("#element").hide(1000, function() {
    alert("Element is now hidden!");
});

Explanation: This code hides the #element over 1 second, then triggers the callback function to display an alert once the element is hidden.

Using Callbacks in Chains

Callbacks can also be used in chained methods to ensure each operation completes before the next begins.

$("#element")
    .slideUp(1000, function() {
        console.log("Slide up completed");
    })
    .slideDown(1000, function() {
        console.log("Slide down completed");
    });

Explanation: Each method in the chain waits for the previous one to finish before starting. Callback functions provide logs at each step.

Example: Callback Functions


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Callback Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div id="box" style="width: 100px; height: 100px; background-color: lightblue;"></div>
    <button id="animateButton">Start Animation</button>

    <script>
        $(document).ready(function() {
            $("#animateButton").click(function() {
                $("#box").animate({ width: "300px" }, 1000, function() {
                    alert("Animation completed!");
                });
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example animates the width of a box element. Once the animation completes, a callback function displays an alert to confirm completion.

Key Takeaways

  • Asynchronous Control: Callbacks ensure code executes only after specific operations are complete.
  • Method Compatibility: Many jQuery methods like hide(), show(), and animate() support callbacks.
  • Chaining: Combine callbacks with chained methods for precise control over complex animations.