totallyNotLizards
totallyNotLizards

Reputation: 8569

How to stop() animation but allow current one to complete

Using jQuery 1.7.2

$(function(){
    $('#parentElem').mouseenter(function(){
        $('.myElem').animate({opacity:1}, 'fast');
    }).mouseleave(function(){
        $('.myElem').stop().animate{opacity:0}, 'slow');
    });
});

In this example, I have an element that fades in on a mouseenter event and then halts and fades out again (on the mouseout) to give a throb effect.

I have a problem however - using the .stop() method, the currently running animation will be interrupted and fade back out again - my 'throb' effect not really working. Of course this is exactly what .stop() is for - however what I really want to do is just clear the queue and let the current animation complete, while adding the fade out animation to the queue.

Any ideas?

P.S I've tried the .clearQueue() method also but this exhibits similar behaviour.

EDIT: Something I really should have mentioned - I need the element to stay faded in while the cursor is over it - so using the callback on the animate function wouldn't solve it. I've updated the code to make it more obvious. Sorry for any confusion.

Upvotes: 2

Views: 2605

Answers (1)

Rich O'Kelly
Rich O'Kelly

Reputation: 41767

You can use the complete callback of the animate method to perform the fadeOut:

$('.myElem').animate({opacity:1}, 'fast', function() {$(this).stop().animate{opacity:0}, 'slow');});

Update

A similar approach can be used to set a flag to ensure that the animate is stopped and then faded out on the later of the mouseout / fade in complete:

(function() {
  var doFadeOut = false;
  var fadeOut = function() {
    if (doFadeOut) {
        $('.myElem').stop().animate({ opacity: 0 }, 'slow');
        doFadeOut = false;
    } else {
        doFadeOut = true;
    }
  };
  $('#parentElem').mouseenter(function() {
    $('.myElem').animate({ opacity: 1 }, 'fast', fadeOut);
  }).mouseleave(fadeOut);
}())

Upvotes: 5

Related Questions