jQuery, calling a callback only once after multiple animations

落爺英雄遲暮 提交于 2019-11-30 02:58:46

You can run the same callback for all of them, but only execute the if clause if none are currently being animated anymore, like this:

  $(".myclass").fadeOut("slow", function() {
    if ($(".myclass:animated").length === 0)
      $("#target").append("<p>All done.</p>");
  });

This just checks if any are still being animated via the :animated selector. If you were animating lots of different things then use the same concept, just add to the selector like this:

$(".myclass:animated, .myClass2:animated")

If you're using it in lots of places, I'd make that callback a onFinish function or something to tidy it up.

Scrat

Look at the discussion on this thread: jQuery $.animate() multiple elements but only fire callback once

The .when()/.then() and the .promise().done(callback()); functions provide a much more elegant solution to the problem of calling a single calllback at the end of all animations.

In my case I have to define

if ($(".myclass:animated").length === 1)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!