TExcelTAD
Home › jQuery › jQuery Callback

jQuery Callback Functions

JavaScript does not wait for animations. When you call .fadeOut(1000), jQuery starts the fade and returns immediately — the next line of your code runs while the element is still fading. If something must happen after the effect finishes, pass a callback function.

The problem

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    #note { padding: 10px; background: #fff3cd; border: 1px solid #e0b400; width: 240px; }
  </style>
</head>
<body>
  <button id="bad">Without callback</button>
  <button id="good">With callback</button>
  <button id="reset">Reset</button>
  <p id="note">Read me, then I will fade away.</p>
  <p id="status"></p>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $("#bad").on("click", function () {
      $("#note").fadeOut(1500);
      $("#status").text("Gone!");          // runs immediately — too early
      console.log("bad: status set while fading");
    });

    $("#good").on("click", function () {
      $("#note").fadeOut(1500, function () {
        $("#status").text("Gone!");        // runs after the fade completes
        console.log("good: status set after fade");
      });
    });

    $("#reset").on("click", function () {
      $("#note").stop(true).show().css("opacity", 1);
      $("#status").text("");
    });
  </script>
</body>
</html>

With the first button, "Gone!" appears while the note is still clearly visible. With the second, it appears exactly when the fade ends.

Callback syntax

Every effect method takes the callback as its last argument:

js
$(selector).hide(speed, callback);
$(selector).slideUp(speed, easing, callback);
$(selector).animate({ props }, speed, callback);
$(selector).fadeTo(speed, opacity, callback);

Inside the callback, this is the DOM element that just finished animating.

Fact Detail
When it runs After the animation completes (also immediately for duration 0)
this The element that finished
How many times Once per element in the set
Arguments None for effect methods

Once per element — watch out

If the selection contains five elements, the callback runs five times. That is great for per-element work, but surprising if you meant "when everything is done":

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    .chip { display: inline-block; padding: 6px 12px; margin: 3px; background: #0769ad; color: #fff; border-radius: 14px; }
  </style>
</head>
<body>
  <button id="clear">Clear chips</button>
  <div id="chips">
    <span class="chip">html</span>
    <span class="chip">css</span>
    <span class="chip">js</span>
    <span class="chip">jquery</span>
  </div>
  <p id="out"></p>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $("#clear").on("click", function () {
      // callback: once per element
      $(".chip").fadeOut(600, function () {
        console.log("callback for", $(this).text());
      });

      // promise: once when ALL elements are done
      $(".chip").promise().done(function () {
        console.log("all chips hidden");
        $("#out").text("Every chip is gone. (" + this.length + " elements)");
      });
    });
  </script>
</body>
</html>

.promise() returns a promise that resolves when all queued animations on the set have finished; inside .done(), this is the whole jQuery object. Since jQuery 3, these promises are compatible with async/await too:

js
await $(".chip").fadeOut(600).promise();
console.log("all done");

Sequencing effects on different elements

Effects on the same element queue automatically. Effects on different elements run in parallel — so callbacks are the way to make them run one after another:

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    .step { display: none; padding: 8px 12px; margin: 4px 0; background: #e8f5e9; border-left: 4px solid #2e7d32; width: 260px; }
  </style>
</head>
<body>
  <button id="go">Run the steps</button>
  <div class="step" id="s1">1. Validating order…</div>
  <div class="step" id="s2">2. Charging card…</div>
  <div class="step" id="s3">3. Order confirmed ✔</div>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $("#go").on("click", function () {
      $(".step").hide();
      $("#s1").fadeIn(500, function () {
        $("#s2").delay(300).fadeIn(500, function () {
          $("#s3").delay(300).slideDown(400, function () {
            console.log("all steps shown");
          });
        });
      });
    });
  </script>
</body>
</html>

Deeply nested callbacks become hard to read ("callback pyramid"). With promises you can flatten the same flow:

js
async function runSteps() {
  await $("#s1").fadeIn(500).promise();
  await $("#s2").delay(300).fadeIn(500).promise();
  await $("#s3").delay(300).slideDown(400).promise();
  console.log("all steps shown");
}

Tip: Callbacks are not only for effects. Event handlers, $.each, and AJAX success handlers are all callbacks — functions you give to jQuery to call later.

Test yourself

Where does the callback go in $("#x").slideUp("slow", ???)?

  1. Before the speed
  2. As the last argument
  3. In a separate .then only
  4. Callbacks are not supported by slideUp

$("li").hide(300, fn) matches 4 elements. How many times does fn run?

  1. Once
  2. Twice
  3. Four times
  4. Never

How do you run code once after ALL elements in a set finished animating?

  1. .callback()
  2. .promise().done(fn)
  3. .end(fn)
  4. .finish(fn)