Tekker Blog

My little home on the internet.

Archive for February, 2009

jQuery Alternating Row Colors, Only Better!

with 2 comments

So, today, I was charged with adding some alternating colors to some results lists in the project I am working on.  Simple enough, right?

$('#tableid tbody tr:odd').addClass('tableodd');

Super simple, yet that wouldn’t work, because there are 2 table rows per result.  I did some googling and found this, which was pretty close to what I needed. In the end, I modified the code found on that page a bit and ended up with the following at the end of the function that actually populated the results table.


var classNames = {
0: '',
1: '',
2: 'tableodd',
3: 'tableodd'
}

$(‘#tableidtbody tr’).not(‘[th]‘).each(function(index) {
$(this).addClass(classNames[index % 4])
});

Works great.  If you need to add any additional rows to your result, then just add another row to classNames and change the index % 4 to how ever many items you have in your classNames array.

Hope someone else will find this useful.

Written by Paul

February 11th, 2009 at 12:38 pm

Posted in