Search code examples
javascriptjqueryslidedownslideupmouseenter

Mouseenter and mouseleave with animation


I make a simple mouse enter and mouse leave animation. When you mouse enter the div. Than the links div is going open. When you mouse out, the div is going closed. I set a animation with slideUp and slideDown.

I have a problem with the animation. There are a lot of .comment divs on the page. When I hover over the items quickly. The slide animation is going crazy and you see the animation a lot of times. How can i fix that? Thanks!

$("#comments .comment .links").hide();
$("#comments .comment").mouseenter(function() {
    $(".links",this).slideDown(300);
}).mouseleave(function() {
    $(".links",this).slideUp(300);
});

Solution

  • Use stop(true) to clear the animation queue on each event:

    $("#comments .comment .links").hide();
    $("#comments .comment").mouseenter(function() {
        $(".links",this).stop(true).slideDown(300);
    }).mouseleave(function() {
        $(".links",this).stop(true).slideUp(300);
    });
    

    Also, you could condense this code by using hover():

    $("#comments .comment .links").hide();
    $("#comments .comment").hover(
        function() { $(".links", this).stop(true).slideDown(300); },
        function() { $(".links", this).stop(true).slideUp(300); }
    );