o_O
o_O

Reputation: 5737

Slide animation using jQuery only works in one direction

http://jsfiddle.net/WEBk2/1/

I have a group of block elements and I'm attaching a slide animation on click. The goal is that the elements continue to slide back and forth smoothly.

<section class="stretch">
    <div class="block blue"></div><div class="block red"></div><div class="block green"></div><div class="block orange"></div><div class="block silver"></div><div class="block teal"></div><div class="block salmon"></div>
</section>
<button class="button-left">Left</button>
<button class="button-right">Right</button>

And the jQuery:

function moveRight() {
        var lastBlock = $(".stretch .block:last-child");
        lastBlock.remove();
        $(".stretch .block:first-child").before(lastBlock);
        $(".stretch .block").each(function(){
            $(this).css("left","0").css("right","0");
            $(this).animate({"left": "+=250px"}, "5000");
        });
    };

    function moveLeft() {
        var firstBlock = $(".stretch .block:first-child");
        firstBlock.remove();
        $(".stretch .block:last-child").after(firstBlock);
        $(".stretch .block").each(function(){
            $(this).css("right","0").css("left","0");
            $(this).animate({"right": "+=250px"}, "5000");
        });
    };
$(".button-right").click(function(){
        moveLeft();
    });

    $(".button-left").click(function(){
        moveRight();
    });

The result I'm getting is only one of the move functions is sliding with animate (moveRight). I can't see why it won't animate with the moveLeft function.

Upvotes: 1

Views: 597

Answers (1)

DGS
DGS

Reputation: 6025

Fiddle

Change moveRight() to

function moveRight() {
    if ($('.stretch .block:animated').length == 0) {
        var lastBlock = $(".stretch .block:last-child");
        var cloned = lastBlock.clone()
        cloned.width(1);
        $(".stretch .block:first-child").before(cloned);
        cloned.animate({
            'width': "250"
        }, "5000", function () {
            lastBlock.remove()
        });
    }
};

And moveLeft() to

function moveLeft() {
    if ($('.stretch .block:animated').length == 0) {
        var firstBlock = $(".stretch .block:first-child");
        var cloned = firstBlock.clone()
        cloned.width(250);
        $(".stretch .block:last-child").after(cloned);
        firstBlock.animate({
            'width': "0"
        }, "5000", function () {
            firstBlock.remove()
        });
    }
};

This achieves your visual outcome at the very least. The clone is necessary if you don't have enough elements to fill the container with one missing from the right hand side.

The check if any of the elements are animated will prevent multiple clones being made of the same element.

Upvotes: 2

Related Questions