CCode for Artists - Miles DeCoster

Coding a color palette

This script uses nested "for loops" to create a grid of 216 divs and assigns each div a backgound color based on the once-popular notion of web-safe colors. These were colors which would appear more or less the same on various computer monitors back when many screens only showed 256 colors. They are just rgb values using the numbers 0, 51, 102, 153, 204 and 255. Here we put that set of numbers in an array and create 3 nested for loops to create the 216 possible numeric combinations. They do not make a particularly attractive set of colors, but that was not really the point. If you click a swatch the color value is read and assigned as the background color of the target div.

The loops are nested, so the outer loop runs 6 times using the 6 numbers from the websafe array. The first nested loop runs 6 times each time the out loop runs for a total of 36 iterations. The next inner loop runs 6 times for each iteration of its parent loop for a total of 216 iterations. Each time through the loop another swatch is added and then assigned a color with a unique set of rgb values.

$(document).ready( function() {
	// use a loop to create a grid of divs with a class of "swatch" appended to the div with id of "palette"
	// assign each swatch a web safe color using the numbers from the array for the rgb values
	var websafe = [0,51,102,153,204,255];
	for (var i=0; i<6; i++) {
		for (var j=0; j<6; j++) {
			for (var k=0; k<6; k++) {
				$('#palette').append("<div class='swatch'></div>"); 
				$('.swatch').eq(swatchCount).css('background-color', 'rgb('+websafe[i]+','+websafe[j]+','+websafe[k]+')'); 
	// copy the color information from the swatch clicked on and apply it to the target div
	$('.swatch').click(function() {
		$('#target').css('background-color', myColor);