jQuery - jQuery Callback

When you run animations or effects in jQuery like hide(), fadeOut(), or slideUp(), they take a little time to complete. But what if you want to do something else right after the effect finishes?

That’s where a callback comes in.

A callback is a function that runs after another function has finished. It makes sure your code runs in the right order—even when animations are happening.


How to Use a Callback in jQuery

Here’s the basic format:

$(selector).effect(speed, function() {
  // This is the callback function
  // It runs after the effect is done
});

Let’s look at a simple example.


Example: Hide a paragraph, then show a message

$("#hideBtn").click(function() {
  $("#myText").hide(1000, function() {
    alert("The text is now hidden!");
  });
});

In this code:

  • $("#myText").hide(1000) hides the element over 1 second.

  • The function() after that is the callback.

  • It runs only after the hiding animation is finished.

Without a callback, the alert might pop up before the animation is complete.


Another Example: Chain Events Correctly

$("#fadeBtn").click(function() {
  $("#box").fadeOut(1000, function() {
    $("#box").text("Now I'm gone!").fadeIn(1000);
  });
});

Here, the box fades out over 1 second. Once it’s done, it changes the text and then fades back in. The callback ensures all that happens in the right order.


Why Use Callbacks?

  • To keep animations smooth and ordered

  • To run code only after something finishes

  • To avoid messy, unpredictable behavior

Callbacks help make sure your webpage responds the way you expect, without rushing or skipping steps.