1

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.

vsync
  • 118,978
  • 58
  • 307
  • 400
T.J.
  • 733
  • 9
  • 27

2 Answers2

1

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.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • 1
    I already answered him..and your answer is confusing anyway and is not what he wants. he doesn't need closures. it's a simple jQuery delay, as I told him in the comments. – vsync Dec 22 '14 at 16:12
1

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'});
});
sriniprash
  • 121
  • 1
  • 7