Below is a loop that creates six boxes with different colors. When clicking on a box, the variable "color" changes to the color of the box. There is an obvious problem with the code and that's closures (all the boxes gets the last class in the array and boxColors[i] isn't possible to use inside the event (undefined).
How can I solve this in an elegant way? Thanks in advance.
var boxColors = ['red', 'green', 'blue', 'yellow', 'white', 'black'];
for (var i = 0; i < boxColors.length; i++){
$('<div/>', {
'class': boxColors[i]
}).appendTo(toolboxSection1).click(function(){
color = boxColors[i];
});
}