Reputation: 803
I'm having a little group iterating over an array with Jquery. I have an array and I want each item in the array to fade in and out (and switch to the next while it's faded out). I can make it loop the appropraite amount of times, but the for loop always shows the last variable, not each one in order.
var x = [1,2,3,4,5];
$("#test").text("test");
var y = 0;
for(var i = 0; i<x.length;i++){
$("#test").delay(1000).animate({opacity:'0'},function(){
$(this).text(i)
}).delay(1000).animate({opacity:'1'});
}
So, the p tag this refers to starts off as "text", then flashed '5' five times instead of counting. I thought the delay would work, but the for loop finishes and doesn't wait for the jquery to complete.
Upvotes: 1
Views: 92
Reputation: 59232
Create a closure
for (var i = 0; i < x.length; i++) {
$("#test").delay(1000).animate({ opacity: '0' }, (function(i) {
return function() { $(this).text(i); }
})(i)).delay(1000).animate({ opacity: '1' });
}
You're creating a self executing function which has the i
stored in its context and then returning a function which also has the access to i
variable due to the closure created.
Upvotes: 1
Reputation: 121
I guess you can implement this with $.each as well:
var x = [1,2,3,4,5];
$("#test").text("test");
$.each(x, function(i) {
$("#test").delay(1000).animate({opacity:'0'},function(){
$(this).text(x[i])
}).delay(1000).animate({opacity:'1'});
});
Upvotes: 1