Add a different class to each list item

August 16, 2011

A recent design I had to build required that each list item in a menu (WordPress) be a different colour. After some head scratching I came up with a method using jQuery.

We start off be making sure our counter is 0. Then loop through each list item. We can get the current item number from jQuery and which element we are currently acting on. Setting the colour variable to be 1 + i means we count from 1 up to the total number of list items. I’m using modulo operator to loop the numbers after 8. Using jQuery we can then add class to the current element. The class could contain any CSS operation. I used this for a spectrum of colours.

    colour=0;
	
	$('.nav ul li').each( function(i, elem) 
	{
	
		colour=1+(i%8);
	
		$(elem).addClass('listitem'+colour);
			
	});
Filed under: Programming — Tags: , , , — admin @ 8:29 pm

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

About me

Jonathan Spicer

My CV

My curriculum vitae and a wealth of other facts about me.

Warhammer Quest tools

Flickering flame effect Flickering flame effect Flickering flame effect

Powered by WordPress