CCode for Artists - Miles DeCoster

This html code has some list items on the page. The jQuery routine generates some small boxes each with a random background color. The number of boxes is based on the number of list items and toggles the background color of the list items to match the box when you click on the box or back to white.

The $(...).index() function returns the index number of a selected item in the array returned by the jQuery function, which is to say, its numerical position in the returned array. For example $('p') selects all of the paragraph tags, so if there happen to be 3 paragraphs they would be returned in an array [p, p, p] at indexes 0, 1, 2. In this example we have 5 divs generated with a class of "myLink" so $('.myLink') returns an array of the 5 divs. We add a click function to the class via $('.myLink').click(function(event) {}); Now we can use either $( or $('.myLink').index(this) to return the index number/position of the particular div clicked on.

The $(...).eq() function is more or less the opposite of the index() function. The eq() function returns the object at the specified location in the array returned by the jQuery selector. So $('li').eq(1) would be the second list item and $('li').eq(whichLink).css('background-color', 'white'); would set the list item at location whichItem (a variable) in the array to a background color of white.

$(document).ready( function() {

	for (var i=0; i < $('li').length; i++) {
    	// generate a random hex number from #000000 to #ffffff
		var randColor= '#'+Math.floor(Math.random()*16777215).toString(16);
        // add a div with the random color as background
		$('nav').append("<div class='myLink' style='background-color:"+randColor+"'></div>");
	// this function checks to see which box is clicked on and changes 
	// the numerically corresponding list item to the same background color
	$('.myLink').click( function(event) {
		var myColor= $('background-color');
		if ($('li').eq(whichLink).css('background-color')!=myColor) {
			$('li').eq(whichLink).css('background-color', myColor);
		} else {
			$('li').eq(whichLink).css('background-color', 'white');