I have a for loop that runs through a selection of li’s via a data attribute.
I want each group of Lis to have a staggered fade in. This works fine until I put the animation inside a setTimeout . Instead of looping through each li, it sticks on the number 5.
JS:
for (i=0;i<6;i++) {
console.log(thisI);
var thisLi = $("li[data-order='"+i+"']");
setTimeout(function() {
TweenMax.to(thisLi,0.4, {css:{opacity:1}});
},200*i);
}
HTMl
<li data-order="1">sometext</li>
<li data-order="1">sometext</li>
<li data-order="2">sometext</li>
<li data-order="3">sometext</li>
<li data-order="2">sometext</li>
<li data-order="3">sometext</li>
CSS
li {
opacity:0;
}
Here’s chromes log when I console.log(thisLi); inside the setTimeout :
<li data-order="5" style="opacity: 0.11640000000000006; ">…</li>
,
<li data-order="5" style="opacity: 0.11640000000000006; ">…</li>
]
By the time the
setTimeoutcallback executes, the loop has already finished soihas reached it’s maximum value. You can use a closure to capture the value ofiat each iteration:Side note: if you’re not declaring
ielsewhere, then it’s leaking into the global scope.