I experience a very weird JavaScript behavior.
I’m using jQuery 1.9 and farbtastic color picker:
While this code works:
$('#colorpicker_1').hide();
$('#colorpicker_1').farbtastic('#color_1');
$('#colorbody_1').click(function(){$('#colorpicker_1').slideToggle()});
$('#colorpicker_2').hide();
$('#colorpicker_2').farbtastic('#color_2');
$('#colorbody_2').click(function(){$('#colorpicker_2').slideToggle()});
$('#colorpicker_3').hide();
$('#colorpicker_3').farbtastic('#color_3');
$('#colorbody_3').click(function(){$('#colorpicker_3').slideToggle()});
$('#colorpicker_4').hide();
$('#colorpicker_4').farbtastic('#color_4');
$('#colorbody_4').click(function(){$('#colorpicker_4').slideToggle()});
this does not work, and i have absolutely no clue, why it does not:
var cstatusIDs = new Array();
cstatusIDs.push(1);
cstatusIDs.push(2);
cstatusIDs.push(3);
cstatusIDs.push(4);
for(var z=0; z < cstatusIDs.length; z++)
{
var cstatus_id = cstatusIDs[z];
console.log(cstatus_id); // outputs 1,2,3,4
$('#colorpicker_'+cstatus_id).hide();
$('#colorpicker_'+cstatus_id).farbtastic('#color_'+cstatus_id);
$('#colorbody_'+cstatus_id).click(function(){$('#colorpicker_'+cstatus_id).slideToggle()});
}
Any ideas?
The problem is the fact that
cstatus_idis defined outside the scope of your click handler, and its value changes each time the loop runs. Since the click handler is not actually evaluated until you trigger a click event, at that time all of the handlers use the last value ofcstatus_id.To work around this, wrap the handler in a closure so that each instance gets its own unique id.