← Back to Chapters

jQuery Callback Tutorial

? jQuery Callback Tutorial

? Quick Overview

Callbacks are functions passed as arguments to other functions and executed only after the first function completes. They are extremely useful in animations and asynchronous tasks.

? Key Concepts

  • Callbacks run after an action finishes
  • They prevent timing-related bugs
  • Widely used in animations and async workflows

? Syntax / Theory

In jQuery, many animation methods accept a callback function that executes once the animation completes.

? Code Example – Hide Then Show

Watch me hide, then show!
? View Code Example
// Hide an element, then execute callback after animation
function hideThenShow() {
$("#callbackBox").hide(1000, function() {
alert("Hide complete!");
$("#callbackBox").show(1000);
});
}

? Interactive Callback Example

I will fade out, then change color, then fade in!
? View Code Example
// Perform fade animation and run callback when fadeOut finishes
function fadeAndChangeColor() {
$("#fadeBox").fadeOut(800, function() {
$(this).css("background", "#ffe082");
$(this).text("Color changed! Now fading in...");
$(this).fadeIn(800);
});
}

⛓️ Multi-Step Sequence (Chained Callback)

You can nest callbacks within each other to create complex, multi-step sequences that fire exactly when you want them to.

I'm a multi-step animation!
? View Code Example
// Nesting callbacks for a 3-step sequence
function runChainSequence() {
  $("#chainBox").slideUp(500, function() {
    // This runs after sliding up
    $(this).css("border-color", "var(--danger)");
    $(this).text("Sequence: Step 2 Complete!");
    
    $(this).slideDown(500, function() {
      // This runs after sliding back down
      alert("All steps finished!");
    });
  });
}

? Live Output / Explanation

Each animation waits until the previous one completes. The callback ensures that color changes and fade-in happen only after fade-out finishes.

? Use Cases

  • Sequential animations
  • AJAX request handling
  • UI feedback after actions complete

✅ Tips & Best Practices

  • Use callbacks to control execution order
  • Keep callback logic simple and readable
  • Split large callbacks into named functions

? Try It Yourself

  • Create multiple animation chains using callbacks
  • Display messages after fade or slide effects
  • Experiment with different animation durations