Matt Dryden
Matt Dryden

Reputation: 14905

How to stop jQuery animation from stacking before previous animation completes?

I don't know how to best explain this, and I'm sure my title doesn't do the job. Here is the problem. I need to build a pullout on the side of the page. When you hover over the tab, it pulls out from the left. When you unhover, it moves back to it's original position. That all works great except for one annoyance. If you scrub your mouse on and off the div quickly, it queues up multiple .animate functions, leaving the tab to pop in and out multiple times. Here is the site with the annoyance as of the time of writing: http://mattandjentry.com/weddings/

Here is my jquery:

$(document).ready(function() {
    $("#session_pullout").css("left", "-370px"); 

    $("#session_pullout").hover(function() {
        $("#session_pullout").animate(
                {"left": "-50"},
                "fast");
        }, function(){
            $("#session_pullout").animate(
                {"left": "-370px"},
                "fast");
        });
});

Upvotes: 0

Views: 386

Answers (2)

Alexander
Alexander

Reputation: 23537

Yet another .stop() question.

Use .stop() to stop the currently-running animation. Optionally, you can call .stop(true) clear the animation queue as well; or, .stop(true, true) to on top of clearing the animation queue to jump to the end of the animation.

$(document).ready(function () {
    $("#session_pullout").css("left", "-370px");

    $("#session_pullout").hover(function () {
        $("#session_pullout").stop().animate({
            "left": "-50"
        }, "fast");
    }, function () {
        $("#session_pullout").stop().animate({
            "left": "-370px"
        }, "fast");
    });
});

Take a look at the parameters of .stop() and see which better fits your need.

Upvotes: 3

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

Use .stop().

$("#session_pullout").hover(function() {
    $("#session_pullout").stop(true, true).animate({
        left: '-50px'
    }, 'fast');
}, function() {
    $("#session_pullout").stop(true, true).animate({
         left: '-370px'
    }, 'fast');
});

This clears the animation queue and forces the next animation to run. You can find the documentation here.

Upvotes: 0

Related Questions