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.

3
  • 2
    do 1000 * (i+1) so the delay will be 1000, then 2000, then 3000... Commented Dec 22, 2014 at 16:09
  • 2
    Read about closures: stackoverflow.com/questions/111102/… Commented Dec 22, 2014 at 16:12
  • 1
    Amir, thanks for the link! Commented Dec 22, 2014 at 16:14

2 Answers 2

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'});
});
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.