Nick
Nick

Reputation: 2551

Animate & preventing animation firing on multiple clicks

http://jsfiddle.net/ghv11Loy/

$('#wobble').click(function(){
  $(this).animate({marginLeft: '+10px'}, {"queue": true, "duration": 100})
         .animate({marginLeft: '-20px'}, {"queue": true, "duration": 100})
         .animate({marginLeft: '+10px'}, {"queue": true, "duration": 100})
         .animate({marginLeft: '-20px'}, {"queue": true, "duration": 100})
         .animate({marginLeft: '+10px'}, {"queue": true, "duration": 100});
});

When I click #wobble multiple times the animations run until they're completed. Is there any way to prevent this from happening?

For example, if I click it 50 times as quick as I can, I'm sat waiting for the animations to run through 50 times. I'd like to be able to click once, and then the animation runs once until it's finished. Then it can run again if it's clicked after the animation has stopped and so on.

Also, is there a cleaner way to animate an element several times as this looks messy to me?

I've tried using .stop() but I don't think it works how I'm expecting it to. I may have done it wrong though.

Any help would be great.

Thanks!!

Upvotes: 1

Views: 41

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to call stop(true, true) on the element to end any animations which are currently running or queued:

$(this).stop(true, true)
    .animate({ marginLeft: '+10px' }, { "queue": true, "duration": 100 })
    .animate({ marginLeft: '-20px' }, { "queue": true, "duration": 100 })
    .animate({ marginLeft: '+10px' }, { "queue": true, "duration": 100 })
    .animate({ marginLeft: '-20px' }, { "queue": true, "duration": 100 })
    .animate({ marginLeft: '+10px' }, { "queue": true, "duration": 100 });

Example fiddle

Upvotes: 2

hsim
hsim

Reputation: 2080

You could set some kind of global boolean value that is false by default. Once the animation fires, validates if it is false, do the animation, set it to true, then set it to false only when the animation has finished playing.

Upvotes: 1

Related Questions