Better Zebra Tables
March 15th, 2009
by Munazza
In large tables it’s often hard to focus on one row, making it hard to extract data from the table.
There are various scripts (client–side as well as server–side) floating around the net that provide the ability to style odd/even table–rows to aid readability of tabular data.
If you’re not interested in how this works then you can download the source code
The original script
Zebra Tables is a script that applies different background colors to odd or even table–rows
Better Zebra Tables
While the previous script applies background–colors to the individual table–cells I think it’s better to apply a class to the table–row itself, then use CSS to style the table–cells.
We also made the script more generic by looping through all the tables in the document, if you just need certain tables to be striped you should use David Miller’s method using id’s or better yet; classes.
The script allows you to style rows using CSS, it uses two classes; The class ‘even’ is used for, well you guessed it, even rows.
The class ‘ruled’ is used for the hover state of a table–row.

Multiple classes
The stripe function now adds the ‘even’ class in a way that existing classes won’t be overwritten, allowing for more complex table–row styles.
Hovers
We wanted to apply a hover-state for rows to make it even easier to distinguish tabular data.
This could’ve been done from CSS alone, but unfortunately IE doesn’t support the :hover pseudo–class on anything other than links.
We implemented Christian Heilmann’s method from The Table Ruler to add hover support to our zebra stiped tables.
The new script
var stripe = function() {
var tables = document.getElementsByTagName("table");
for(var x=0;x!=tables.length;x++){
var table = tables[x];
if (! table) { return; }
var tbodies = table.getElementsByTagName("tbody");
for (var h = 0; h < tbodies.length; h++) {
var even = true;
var trs = tbodies[h].getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++) {
trs[i].onmouseover=function(){
this.className += " ruled"; return false
}
trs[i].onmouseout=function(){
this.className = this.className.replace("ruled", ""); return false
}
if(even)
trs[i].className += " even";
even = !even;
}
}
}
}
window.onload = stripe;
Note: I have tested this script, and it works well in IE5+, Firefox 1.0 and Opera 7 — all on windows.
If you don’t need table–row hovers you can safely remove these lines:
trs[i].onmouseover=function(){
this.className += " ruled"; return false
}
trs[i].onmouseout=function(){
this.className = this.className.replace("ruled", ""); return false
}










