I have a loop in Jquery:
var fadeTime=500;
css_id=0;
$.each(my_array, function (i, d_U) {
css_id++;
an_v=d_U[1];
an_d=d_U[4];
do_c_function("id_344",true,true);
$("#box_"+css_id).fadeIn(fadeTime,function(){
//this stuff will happen once the fadein is complete
$("#box_"+css_id).animate({top: '-50px'},fadeTime,function(){
//this stuff will happen once the animate is complete
alert("#box_"+css_id);//for debugging
});//end of animation
});//end of fadein
});//end of each loop
Now as you’ve probably noticed, I’m trying to make the loop animate different divs each time using the css_id variable and ++; (add 1) to it each time the loop runs.
Thing is, css_id reaches a high value before any of the code below has even been executed once. So when its time to animate, Jquery will try to animate #box_210 when its supposed to animate #box_1.
Is there any way to make it only execute the css_id++; line once, then the animate lines get executed, and only then again with the css_id++; line…and so on.
I’ve tried to put the css_id++; line in a call back with both the animations but that seems to not work as well.
Thanks
Your animate callback function is forming a closure over
css_idand therefore storing a live reference tocss_id, not merely the value this variable holds at the moment the animation loop is created.Since all parameters are passed by value in JavaScript, you can use jQuery’s data function to break the closure, and take a snapshot of the css_id value at that time.