0

Possible Duplicate:
Variable in JavaScript callback functions always gets last value in loop?

I am not able to pass the value of k to the callback function of fadeOut function. my loop is as given below.

 for(var k=0;k<image1.length;k++)
 {

    $(img[k]).fadeOut(200,function(k) {
        alert(k);
        $(this).attr('src', image2[k]);
        $(this).fadeIn(200);
    });
  }
0

2 Answers 2

4

The jQuery fadeOut function takes a callback function with no arguments. From the jQuery documentation, "The callback is not sent any arguments". If you want to capture the value of k, do something like the following:

for(var k=0;k<image1.length;k++) {
    (function(k) {
        $(img[k]).fadeOut(200,function() {
            alert(k);
            $(this).attr('src', image2[k]);
            $(this).fadeIn(200);
        });
    })(k);
}
Sign up to request clarification or add additional context in comments.

1 Comment

10x for the help works perfect..
3

You'll have to do something like this to give the callback access to your variable:

for (var k = 0; k < image1.length; k++) {
    (function(k) {
        $(img[k]).fadeOut(200, function() {
            alert(k);
            this.src = image2[k];
            $(this).fadeIn(200);
        });
    })(k);
}

1 Comment

10x @Blender..this too works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.