Nils
Nils

Reputation: 3

Issue with jQuery when using animate while adding new content

The problem occurs when I try to hit the right "next" button. My div's start to slide but when I've hit the butten a couple of times I start to see these blank White spaces between my div's. Thats not suppose to happen. How could this be solved. I've provided a link to jsfiddle.

var  x = ["blue", "red", "black", "green", "orange"];
    var i = 0;
    $(document).ready(function(){


        $("#right").click(function(){
            if (i === x.length) {
            i = 0;
            }

            $(".slide2:last-child").after("<div class='slide2' style='background-color:" + x[i] + ";'></div>");
            $(".slide2").animate({right:'+=100%'}, 1000);
            //$(".slide2:last").remove();   



            i++;        
        });
    });

Upvotes: 0

Views: 38

Answers (1)

Yoann
Yoann

Reputation: 3060

It is essentially because you're animating every slide individually.

If you wrap your elements inside another, and animate only this one instead, you'll have a more consistent animation :

HTML :

<div id="three">
    <span id="left"><</span>
    <span id="right">></span>
    <div class='container'>
        <div class="slide2"></div>
        <div class="slide2" style="background-color:olive;"></div>
    </div>
</div>

JS :

var  x = ["blue", "red", "black", "green", "orange"];
var i = 0;
$(document).ready(function(){
    $("#right").click(function(){
        if (i === x.length) {
            i = 0;
        }
        $(".slide2:last-child")
            .after("<div class='slide2' style='background-color:" + x[i] + ";'></div>");
        $(".container")
            .animate({left:(-i*100)+'%'}, 1000);
        i++;        
    });
});

Updated JSFiddle.

Upvotes: 3

Related Questions