jquery callback function only working on last loop -
for(var i=0; i<barvalues.length; i++) { actualbarheight = math.floor((barvalues[i]/chartmaxy)*barchartheight); var barchartid = "#barchart" + (i+1) $(barchartid + " .value span").css('background-color','transparent'); $(barchartid + " img").animate({ height: actualbarheight }, 500, function(){$(barchartid + " .value span").css('background-color','white');} ); $(barchartid + " .value span").html("$"+math.floor(barvalues[i])); $(barchartid + " .value").css("bottom",actualbarheight+"px"); $(barchartid + " .ylabel").html(chartmaxy); };
the above bit of jquery inside loop. each iteration of loop following:
- sets background of span
- animates object
- upon finishing, resets background of span
i'm using call function reset background finishes animation before doing so. however, ends affecting last span referenced in loop.
if move bit of code outside of callback, effects every span through every iteration of loop, (but doesn't wait animation in case)
i'm guessing issue has building selector inside function inside animate function. there bad syntax in markup?
edit (per russ's suggestion, include full loop in above sample)
this common problem experienced when combining closures loops. javascript late-binding language , loops not introduce new scope. so:
for (var i= 0; i<5; i++) { $('#thing'+i).click(function() { alert(i); }); }
there 1 i
variable in code. starts @ 0
, once assignment-loop finished left @ 5
. click event on #thing0
element ever going fired after loop has finished executing, point value of i
5
. not define-time value 0
might have expected.
this applies not loop variable other variables re-assigning each time round loop too. in example value of barchartid
inside animation callback function id associated last element in loop.
the usual workaround take copy of loop variable's value @ define-time using structure does introduce new scope, namely function:
$(barchartid + " img").animate({height: actualbarheight}, 500, function(barchartid) { return function() { $(barchartid + " .value span").css('background-color','white'); }; }(barchartid));
Comments
Post a Comment