Adding alternating table row colors dynamically with prototype

Alternative table row colors (also known as zebra tables) are very handy.  Recently I ran into an issue with redmine where it generates tables in a way that prevents you from tagging the rows as “even/odd” when you create them.

You can fix this after the fact with the following prototype function (redmine is a rails app, so I used prototype, it should be pretty easy to do in jquery as well).

function colorTable() {
    var EvenOddCount = 0;
    $$(‘.splitcontentleft tr’).each(function(element) {
            if(EvenOddCount % 2 == 0){
                element.className = “even”;
            }else{
                element.className = “odd”;
            }
            EvenOddCount++;
        });
}

I use your own css selector where appropriate in the $$ function.  Then you can set tr.even and tr.odd in your css file and give it your color scheme.  Just set onload=”colorTable();” in your body declaration, and off you go.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s