Search code examples
javascriptjqueryhtmlcsssiblings

Stop animation on .siblings()


I'm creating a page when you hover a div. That div will grow in size (width) and the other divs (siblings) will be smaller in size (width).

I use a mouseenter and a mouseleave. But I can't get the .stop() function working. When you hover one and less than a sec another one. The old one will not stop.

Live example:
http://jsfiddle.net/5kyw9ya7/7/

Code:
Html:

<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>

Css:

body, html {
    margin:0px;
    overflow:hidden;
}
div {
    float:left;
    height:100vh;
    top:0;
    bottom:0;
}
.one {
    background-color:orange;
}
.two {
    background-color:yellow;
}
.three {
    background-color:red;
}
.four {
    background-color:purple;
}
.five {
    background-color:green;
}

Jquery:

var breedte = $(window).width() / 5;
$("div").css("width", breedte);

$("div").stop()
    .mouseenter(function () {
    $(this).animate({
        width: "+=100"
    });
    $(this).siblings().animate({
        width: "-=25",
    });
    $(this).siblings().css(
        "backgroundColor", "grey");
})
    .stop().mouseleave(function () {
    $(this).animate({
        width: "-=100"
    });
    $(this).siblings().animate({
        width: "+=25"
    });
    $(this).siblings().css(
        "backgroundColor", "");
});

Solution

  • It works better if you put .stop() in the event handlers. You should also call it as .stop(true,true) in order for it to finish the animation. Otherwise, the sizes get all messed up. See the documentation.

    var breedte = $(window).width() / 5;
    $("div").css("width", breedte);
    
    $("div").stop()
        .mouseenter(function () {
        $(this).stop(true,true).animate({
            width: "+=100"
        });
        $(this).siblings().stop(true,true).animate({
            width: "-=25",
        });
        $(this).siblings().css(
            "backgroundColor", "grey");
    })
        .stop().mouseleave(function () {
        $(this).stop(true,true).animate({
            width: "-=100"
        });
        $(this).siblings().stop(true,true).animate({
            width: "+=25"
        });
        $(this).siblings().css(
            "backgroundColor", "");
    });
    

    Updated fiddle: http://jsfiddle.net/5kyw9ya7/10/