Search code examples
javascriptjqueryslide

how do I run code after the last element has completed its jQuery slideup effect?


If I have a .slideUp() that runs against a class that belongs to multiple elements, how do I run code after the last element has completed its slideup effect? It seems like using the built in complete callback runs the callback after every individual element completes its slideup instead of doing it once when theyre all complete.

Here's some example code that might help illustrate the issue I'm having:

$("#my-button").click(() => {
  $(".my-target-class").slideUp(400, () => {
    console.log("I only want this to fire once...");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
    <div class="my-target-class">div 1</div>
    <div class="my-target-class">div 2</div>
    <div class="my-target-class">div 3</div>
    <button id="my-button">try me</button>
</section>


Solution

  • In jQuery, this will actually run your slideUp (including its callback) on all elements, so the callback also fires several times.

    You can use .promise to get a promise for the whole operation, and react on it being done:

    $("#my-button").click(() => {
      $(".my-target-class").slideUp(400).promise().done(() => {
        console.log("I only want this to fire once...");
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <section>
        <div class="my-target-class">div 1</div>
        <div class="my-target-class">div 2</div>
        <div class="my-target-class">div 3</div>
        <button id="my-button">try me</button>
    </section>