Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop all previous animations in Jquery before executing new one?

I am just experimenting something with JQuery.

I have an image which fades into another image as mouseOver() occurs and fades back on mouseOut()

It works great, except if you are moving your mouse over the link again and again, say 5 times, the image fades in and out repeatedly, 5 times while you just sit there and wait for it to get over with this crazy behaviour.

To stop this behaviour, I tried to use a flag and start the animation ONLY if it isnt already animating, but, guess what? If, say, I have 4 such buttons, and on each button mouseover i am fadingIn a different image, that animation will be ignored since the flag is false.

so Is there a way to stop all the previous animations before executing new ones? I am talking about the normal fadeIn() and slideDown() functions in JQuery


EDIT: Adding code from link.

<a href="javascript:void(0);" onMouseOver="mouseOverOut(false);" onMouseOut="mouseOverOut(true);">Tick</a>

javascript

function mouseOverOut(t)
{
    if(t)
    {
        $('.img1').fadeIn();
        $('.img2').fadeOut();
    }
    else
    {
        $('.img1').fadeOut();
        $('.img2').fadeIn();
    } 
}
like image 406
LocustHorde Avatar asked Nov 04 '10 11:11

LocustHorde


2 Answers

Using .stop() with fadeIn/Out can cause the opacity to get stuck in a partial state.

One solution is to use .fadeTo() instead, which gives an absolute destination for the opacity.

function mouseOverOut(t) {
    if(t) {
        $('.img1').stop().fadeTo(400, 1);
        $('.img2').stop().fadeTo(400, 0);
    }
    else {
        $('.img1').stop().fadeTo(400, 0);
        $('.img2').stop().fadeTo(400, 1);
    } 
}

Here's a shorter way of writing it.

function mouseOverOut(t) {
    $('.img1').stop().fadeTo(400, t ? 1 : 0);
    $('.img2').stop().fadeTo(400, t ? 0 : 1);
}

Or this may work. Test it first, though.

function mouseOverOut(t) {
    $('.img1').stop().fadeTo(400, t);
    $('.img2').stop().fadeTo(400, !t);
}

EDIT: This last one seems to work. The true/false is translated to 1/0. You could also use .animate() directly.

function mouseOverOut(t) {
    $('.img1').stop().animate({opacity: t});
    $('.img2').stop().animate({opacity: !t});
}
like image 185
user113716 Avatar answered Nov 11 '22 03:11

user113716


Did you already try stop() ?

Description: Stop the currently-running animation on the matched elements.

like image 39
Dr.Molle Avatar answered Nov 11 '22 03:11

Dr.Molle