4

I am using jQuerys animate function on a plugin, on many elements simulatensly with different durations for each element. I want to know if any animation is running or if there is no animation at all. So i came up with this:

if( $div1.is(':animated') || $div2.is(':animated') || $div3.is(':animated') ) return true;
else return false;

or this:

if( $div1.add($div2).add($div3).is(':animated') ) return true;
else return false;

Which is better???

Do you know any other method???

I dont want this code $("*").is(':animated'); because it will check all animations and from other plugins animations.

Have in mind that I have many elements, not just 3.

Thanks for reading...

gadlol
  • 1,343
  • 2
  • 15
  • 24

3 Answers3

7

I would go with the second as it is less code to read and think about it.

Generally, DRY is better.

You could also refactor that...

return $div1.add($div2).add($div3).is(':animated');
alex
  • 479,566
  • 201
  • 878
  • 984
4

Perhaps you could put a class on the divs you would like to check for animation?

if ($(".myclass").is(":animated")) return true;
Ben Cull
  • 9,434
  • 7
  • 43
  • 38
1

I'd probably keep it explicit, to save cycles. Each time you animate, increment numberOfTotalAnimations. In the end of animation callback, decrement it. That is if you really need speed here. Otherwise, I like @Ben's class proposal.

UPDATE with an example, by request:

var numberOfTotalAnimations = 0;

numberOfTotalAnimations++;
$('#thing').animate({
    opacity: 0.1
  }, 2000, function() {
    numberOfTotalAnimations--;
  });

if (!numberOfTotalAnimations) {
  console.log("Everything's quiet.");
} else {
  console.log("Something's moving.");
}

It's not pretty, it's error-prone (in that you can forget to increment or decrement the counter) - but it's fast.

Amadan
  • 191,408
  • 23
  • 240
  • 301