8

Is their a way to detect if an element is animating or detect if values of an element is changing?

Because I need to trigger a function if an element is animating. Not onComplete of animate.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Jorge
  • 5,610
  • 18
  • 47
  • 67

2 Answers2

24

The following returns true when the selected element is animating:

var isAnimating = $("#someid").is(':animated');

More detail:

http://api.jquery.com/animated-selector/
and/or
http://api.jquery.com/animate/
step: A function to be called after each step of the animation.

David Sherret
  • 101,669
  • 28
  • 188
  • 178
Andy
  • 29,707
  • 9
  • 41
  • 58
  • Andy please can I just clarify my understanding of pseudo-selector :animated. The behaviour that I am seeing is that once the element has started to be animated is(:animated) is true even when the element has been returned to it's starting point. I am therefore using step to detect when an animation has reached it's animated position. Is there a way to toggle the pseudo selector on and off? – codepuppy Nov 06 '12 at 09:51
  • @codepuppy this is strange, i made a test here: http://jsfiddle.net/aPk3y/1/ and it returns the correct value. I don't think there's an easy way to manipulate :animated directly. – Andy Nov 06 '12 at 17:52
  • Andy thanks for this example. OK so I can see it works for you. Therefore I must be making a mistake somewhere. I will go back and review my test again. – codepuppy Nov 07 '12 at 11:30
  • @codepuppy maybe you could show some of your code or create a jsfiddle or even link to your page, then i could have a look at it. – Andy Nov 07 '12 at 17:09
  • Great and quick simple answer! – Forged Dec 06 '22 at 14:45
1

A simple way would be adding a global boolean that gets set to true as soon as the animation starts. Then you add a callback function to the animation that sets it to false as it finishes.

var running = false;

$('#start').click(function(){

    running = true;

    $('#target').animate({opacity: 0.5},'slow',function(){

        running = false;

    });

});

Edit: Oh I guess there's a selector for it.

Kokos
  • 9,051
  • 5
  • 27
  • 44
  • 1
    If you use this method, take notice of how you use it because in unique situations it could cause a race condition. Example: `1. Click start button (1) -- running = true -- t=0ms` `2. Click start button (2) -- running = true -- t=200ms` `3. Animation (1) finishes -- running = false -- t=600ms` `4. Animation (2) running -- running = false -- 600ms < t < 800ms` `5. Animation (2) finishes -- running = false -- t=800ms` – David Sherret Dec 30 '12 at 19:25