HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery Callback Functions

JavaScript statements are executed line by line. However, with effects, the next line of code can be run even if the effect is not finished. This can create errors. A **callback function** is executed only after the current effect is 100% finished.


The Problem: Synchronous Execution

If you have an alert right after a hide() method, the alert will pop up **before** the hiding animation is done. This happens because JavaScript doesn't wait for the animation to finish.

Wrong Way (No Callback)
$("p").hide("slow");
alert("Finished!");

The alert will show up while the paragraph is still visible and fading.

Right Way (With Callback)
$("p").hide("slow", function() {
  alert("Finished!");
});

The alert will only appear after the paragraph is completely hidden.


Syntax

A callback function is passed as the last argument to an effect method.

$(selector).hide(speed, callback);

Common Use Case: Chaining Logic

You might want to remove an element from the DOM only after it has finished fading out to avoid a "jumping" UI.

$("button").click(function() {
    $("#message").fadeOut("slow", function() {
        // This code runs only AFTER fadeOut is complete
        $(this).remove(); 
    });
});
Why this matters: Using callbacks makes your website feel more "stable." It prevents elements from disappearing instantly when they should be transitioning, and ensures your logic follows the visual state of the page.

Callbacks with Multiple Elements

If your selector matches multiple elements (e.g., $("p")), the callback function will be executed **once for each** hidden element. If you have 5 paragraphs, a callback alert will pop up 5 times!

// Warning: This will alert once per paragraph!
$("p").hide("slow", function() {
    alert("One paragraph hidden");
});
Pro Tip: For complex animations involving many elements where you only want the callback to run **once at the very end**, you can use the .promise().done() method. (Stay tuned for advanced sections!)

Key Points to Remember

  • Timing: Callbacks prevent code from running too early during an animation.
  • Syntax: Pass a function as the final parameter to any jQuery effect.
  • Order: Transitions take time (background), but JS execution is instant (foreground). Callbacks bridge this gap.
  • $(this): Inside the callback, $(this) refers to the element being animated.
  • Always use callbacks when one action depends on the completion of a previous transition.