user1282226
user1282226

Reputation:

jQuery: Stop() Event-handling Issue Regarding Animate() Complete

Let's say I have these two functions:

$(".a").animate(
        {"left":"100%"},
        {duration:10000, complete:function(){
             //Something is triggered!! e.g 
             alert("a");
            //Please note: In actual case it is never as simple as alert("a").
        }}
);

$(".b").mouseover(function(){
    $(".a").stop().animate({"top":"100px"},{duration:5000});
});

However, I can't set the second function this way:

$(".b").mouseover(function(){
        //something happens! e.g
        alert("a");
        $(".a").stop().animate({"top":"100px"},{duration:5000});
    });

I've tried stop()'s jumpToEnd parameter and it is not ideal

Whenever .b is mouseover-ed , .a's animte would complete instantly and .a would be shifted to left:100%. I want it to stop at where it is and yet alert("a") before second animate being triggered


I would be extremely grateful if someone can provide a fast and easy solution for this!

Upvotes: 0

Views: 616

Answers (2)

Imdad
Imdad

Reputation: 6032

$(".a").animate(
        {"left":"100%"},
        {duration:10000, complete:myAfterWork} // Use the function name only
);

$(".b").mouseover(function(){
    myAfterWork();
    $(".a").stop().animate({"top":"100px"},{duration:5000});
});

function myAfterWork()
{
  if($(".a").is(":animated"))
  {
    //Access $(".a") here and do your job

    //Note if you use $(this) in place of $(".a") it will be different 
    //when called from .a's animation than from .b's animation
  }

}

Upvotes: 1

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14747

You can check if the element is currently animating by filtering it against :animated.

$('.b').mouseover(function () {

    // if NOT animating, then terminate
    if (!$('.a').is(':animated')) { return; }

    // carry on

});

Upvotes: 1

Related Questions