jQuery Callback

jQuery Callback Functions

JavaScript executes code line by line, moving to the next line immediately.

Because jQuery animations take time to finish, the next line of code can execute while the animation is still running.

This can create massive errors and unpredictable behavior on your website.


What is a Callback?

To prevent these errors, jQuery provides Callback functions.

A Callback function is executed strictly after the current animation is 100% complete.

You place the callback as a parameter inside the effect method.


Example With Callback

Here is how to properly trigger an alert only after the element has completely hidden itself.

Proper Callback Execution:

$("button").click(function(){
  $("p").hide("slow", function(){
    alert("The paragraph is now hidden");
  });
});

Example Without Callback (The Wrong Way)

If you don't use a callback, the alert will pop up immediately.

The paragraph will still be hiding in the background while the alert is blocking the screen.

Without Callback:

$("button").click(function(){
  $("p").hide("slow");
  alert("The paragraph is now hidden"); // This triggers too early!
});

Why Callbacks Matter

Callbacks are essential for chaining complex logic together.

If you want to hide an element, delete it from the database, and show a success message, you must wait for the hiding to finish first.

Always use a callback when executing code that depends on the result of an animation.


Exercise 1 of 1

?

When is a jQuery callback function executed?