CCode for Artists - Miles DeCoster

Coding a color palette

This script uses nested "for loops" to create a grid of 1331 (11*11*11) divs and assigns each div a backgound color using 11 evenly distributed numbers for the rgb values. While the result produces many more colors than the “web-safe” example, the script is almost identical. In theory we could display all 16,777,216 colors in 24-bit rgb color space, but it would take a while for the page to load (I tried it, of course, but the server timed out). Here is a link to a version that shows 15,000+ colors, but it will take a few minutes to load: Lots of colors!

The loops are nested, so the outer loop runs 11 times using the 11 numbers from the number array. The first nested loop runs 11 times each time the out loop runs for a total of 121 iterations. The next inner loop runs 11 times for each iteration of its parent loop for a total of 1313 iterations. Each time through the loop another swatch is added and then assigned a color with a unique set of rgb values. Here is a slight variation which changes the order of the colors: Same colors - different order


<script>
$(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 color using the numbers from the array for the rgb values
	swatchCount=0;
	var websafe = [0, 25, 51, 76, 102, 127, 153, 178, 204, 228, 255];
	for (var i=0; i<11; i++) {
		for (var j=0; j<11; j++) {
			for (var k=0; k<11; k++) {
				$('#palette').append("<div class='swatch'></div>"); 
				$('.swatch').eq(swatchCount).css('background-color', 'rgb('+websafe[i]+','+websafe[j]+','+websafe[k]+')'); 
				swatchCount++;
			}
		}
	}
	// copy the color information from the swatch clicked on and apply it to the target div
	$('.swatch').click(function() {
		myColor=$(this).css('background-color');
		$('#target').css('background-color', myColor);
		$('#info').html($(this).css('background-color'));
	});
});
</script>