December 4, 2006

Alternating Table Row Color Problem

I've been struggling with finding a good way to create a table that works cross browsers with alternating row colors. I don't want each row identified with a different class - because I don't want future inserts into the table to require changing the classes of each subsequent row.

This is where the script I used came from:

function alternate(id){
if(document.getElementById){ //check that browser has capabilities
if(document.getElementsByTagName){ var table = document.getElementById(id); var rows = table.getElementsByTagName("tr"); for(i = 0; i < rows.length; i++){ //manipulate rows
if(i % 2 == 0){
rows[i].className = "even";
rows[i].className = "odd";
} }


Then I set two classes with CSS:

Then in the HTML:
<body onLoad="alternate('ContactTable')">

This seems to work on IE and NOT on Firefox. I think there's an error in the code. What I did was take the code the site gave - and stripped it down so it didn't have the other alternating row color options. I'm not enough of a javascript person to trouble shoot.

The page with the code I started with works fine in Firefox (I downloaded this from the site mentioned above).

This CSS table gallery gives some very good ideas about ways to make CSS tables look good.