March 2, 2007
Alter Table Row Background Colors
Many sites that present tabular data use alternating background colors to increase the readability of that data. The obvious solution is to hardcode every second row to ensure it had a different background color. But if you want the table to be dynamic, meaning that it would be possible to add a new row in the middle of the table without changing the background color attribute of the rows that followed requires a little JavaScript.
A fairly simple function is all you need:
function alternate(id) { // object detection if (document.getElementsByTagName) { // reference the table (id) and the rows ("tr") var table = document.getElementById(id); var rows = table.getElementsByTagName("tr"); // loop through the table rows for(i = 0; i < rows.length; i++) { // %, gives remainder in division if (i % 2 == 0) { rows[i].className = "even"; } else { rows[i].className = "odd"; } } } }
Then add your CSS styles to your stylesheet:
.odd {background-color: white;} .even {background-color: gray;}
This simple example shows how it would look and here is the code (.zip) as well.
Posted in:
