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);
    });
  }
Community
  • 1
  • 1
Arun Killu
  • 13,581
  • 5
  • 34
  • 61

2 Answers2

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);
}
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
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);
}
Blender
  • 289,723
  • 53
  • 439
  • 496