I’m working on a codecademy.com lesson that uses jQuery to create a color picker, which the user can use to select the background and border color of a div. You can see what it’s supposed to look like here (at exercise 4-3). http://www.codecademy.com/courses/basic-jquery/3#!/exercises/2 There’s basically a row of colored boxes that you click on to choose the color of the different attributes of the main div. In total, there are three rows (each with many colored boxes) to choose the color of the three attributes of the div that we can style.
My question concerns the makeColorOption function. It’s adding a class “colorOption” for the color parameter, however, I don’t ever see this function called with a color passed to it. I’m assuming it must be called once for each color in the array, but I don’t see that happening anywhere.
Can anyone explain if I’m missing something?
$('document').ready(function(){
//make the color pickers
var colors = ['red','green','blue','yellow','black','white'];
function makeColorOption(color) {
return $('<div/>')
.addClass("colorOption")
.html(color)
.css('background-color',color);
}
$.each(colors,function(i,v) {
$('div.colorPicker').append(
$('<div/>')
.addClass("colorOption")
.html(v)
.css('background-color',v)
);
});
$('div.colorPicker').append($('<div/>').addClass('clearfix'));
$('div.colorOption').click(function(){
var $this = $(this);
var target = $this.closest('div.colorPicker').data('styleTarget');
switch(target) {
case 'background-color':
setBackgroundColor($('#toy'),$this.html());
break;
case 'text-color':
setTextColor($('#toy'),$this.html());
break;
case 'border-color':
setBorderColor($('#toy'),$this.html());
break;
default:
alert('hi');
}
});
});
You’re not missing anything, the
makeColorOptionfunction is not used. The color pickers are being created by the$.each(colors,function(i,v)loop, whose body duplicates whatmakeColorOptiondoes.You could change that loop to:
and it would be equivalent.