Sharda Singh
Sharda Singh

Reputation: 747

Stop previous animation before start of next animation in JQuery

I have made four span which on mouseOver animate to top:20px and on mouseOut animate back to top:-20px.

I have written this code:

    $(".pull_down").mouseover(function(){
        $(this).animate({top:'20px'});  
    });
    $(".pull_down").mouseout(function(){
        $(this).animate({top:'-20px'}); 
    });

All the span has same class pull_down which has this CSS style:

.pull_down
{
    -webkit-msie-transform: rotate(-90deg);
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -o-transform: rotate(-90deg);


    background:#900;
    color:#FFF;
    font-size:20px;
    text-transform:capitalize;
    font-weight:bold;
    padding:5px;
    position:absolute;
    border:#000 solid 2px;
    border-bottom-left-radius:10px;
    padding-right:100px;
    z-index:500;
    width:100px;
}
.pull_down:hover
{
    cursor:pointer;
}

Basically this is of no use.

The problem lies here is, if the mouse is passed over these elements more than 1 time, say 7 times, then these animations are queued and this looks awkward

So what I wanted was when I hover over a span it start its animation and when I switch over another span the last span is restored to its position.

One Example is here

I also read related posts for .stop() but was unable to figure it out how to do this.

Upvotes: 3

Views: 2758

Answers (2)

Michael Angstadt
Michael Angstadt

Reputation: 890

One of the awesome properties of jQuery is method chaining which allows for the serial processing of timed events.

If you rewrite your code using .stop() you should be able to do the trick.

Like this

$(".pull_down").mouseover(function(){
    $(this).stop().animate({top:'20px'});  
});
$(".pull_down").mouseout(function(){
    $(this).stop().animate({top:'-20px'}); 
});

This will clear the animation queue for the selected DOM object and subsequently add the animation to be processed immediately.

To stop all of the other spans, just reuse the selector inside the call like this

$(".pull_down").mouseover(function(){
    $(".pull_down").stop();
    $(this).animate({top:'20px'});  
});
$(".pull_down").mouseout(function(){
    $(".pull_down").stop();
    $(this).animate({top:'-20px'}); 
});

Upvotes: 6

user405398
user405398

Reputation:

Use .stop( [clearQueue ] [, jumpToEnd ] )

$(".pull_down").mouseover(function(){
    $(this).stop(true, true).animate({top:'20px'});  
});
$(".pull_down").mouseout(function(){
    $(this).stop(true, true).animate({top:'-20px'}); 
});

Upvotes: 1

Related Questions