Alter Table Row Background Colors Using JavaScript

Many sites that present tabular data use alternating background colors to increase the readability of that data. And as I developed a site, I realised I wanted to do that, too. The problem? In my case the table was not generated by a server side application or script of which you can find numerous examples on the Web.

The obvious solution was to hardcode every second row to ensure it had a different background color. But I wanted the table to be dynamic, so that it was possible to add a new row in the middle of the table without changing the background color attribute of the rows that followed.

My solution uses JavaScript, as CSS3 isn’t truly a viable option yet. Browsers today still struggle to support CSS1 and CSS2. Even though HTML tables aren’t recommended for Web page layout, they are still perfectly suited to the presentation of tabular data. In this tutorial, I’ll present three examples based on the same idea. I have tested the solutions in IE6, Firefox 1.0, Mozilla 1.7.3 and Opera 7.54 on the Windows platform only.

Getting Started

Let’s start with an ordinary html table. Whether the table contains head/foot elements doesn’t matter in this case:

<table id="theTable"> 
<tr><td>0 - some txt</td></tr>
<tr><td>1 - some txt</td></tr>
 <tr><td>2 - some txt</td></tr>
 <tr><td>3 - some txt</td></tr>
 <tr><td>4 - some txt</td></tr>      
</table>

Now, we need to check that the browser is fairly new and has the necessary JavaScript capabilities (i.e. W3C DOM support). The following line performs this check, disqualifying Netscape 4 and others of that generation. Such browsers will make no attempt to color the table.

if(document.getElementById)

Also note that common to all these examples is this code:

var table = document.getElementById(id);   
var rows = table.getElementsByTagName("tr");  
for(i = 0; i < rows.length; i++){          
   //manipulate rows
     ...
Example 1

This first example uses a style element through which we have defined two classes for background colors:

<style> 
 .odd{background-color: white;}
 .even{background-color: gray;}
</style>

The style is flexible: it could just as well define something else, such as that every second row should display in italics. The complete function looks like this:

function alternate(id){ 
 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";
     }else{
       rows[i].className = "odd";
     }      
   }
 }
}

Here, %, the modulo operator, gives us the remainder in division.

The above function should be called from the onload event of the body tag:

<html> 
...
<body onload="alternate('thetable')">
<table id="thetable">
<tr><td>...</td></tr>
</table>
...

The result could look something like this:

1457_rowcolor1

Example 2

Let’s move on to the next example — something a little more adventurous. Instead of using just two alternating colors, I want to use several. Let’s add an array that holds all these colors.

Since a limited number of colors have a defined name in HTML, we’ll switch to hexadecimal values. The resulting colors will be made up of three values: red, green, and blue. White is achieved when all three colors are turned on at max: #ffffff. The opposite, black, is #000000.

//various gray shades  
var colors = new Array('#ffffff','#dddddd','#aaaaaa','#888888');

The row-manipulating code will comprise just a single line, but instead of copying and pasting the same code, we’ll make a separate function call:

for(...  
//manipulate rows  
doMultiple(rows[i], i);  
...  
 
function doMultiple(row, i){  
row.style.backgroundColor = colors[i % colors.length];  
}  
 
function doAlternate(row, i){  
 if(i % 2 == 0){  
   row.className = "even";  
 }else{  
   row.className = "odd";  
 }  
}

Here, I’ve also added a function for Example 1 called doAlternate. This makes it easier to switch between the different methods by which we can alternate the table’s row colors.

As seen in the above fragments, it’s possible to set for the rows the CSS class name, or a specific attribute of an HTML tag:

rows[i].className  
rows[i].style.backgroundColor

The result of Example 2 might appear as shown below:

1457_rowcolor2

Example 3

The final example shows a really colorful variant in which the color is calculated depending on the number of rows in the table, the start color and a given factor.

First, we need to set a few variables:

var color = 255;     //starting color (in decimal)  
var steps = 20;    //the factor, a "distance" between colors  
var down = true;  //direction, if going up or down when calculating //color value

We now add a new function, doGradient.

function doGradient(row){  
 bgcolorValue = padHex() + bgcolor.toString(16)  
   + padHex() + bgcolor.toString(16) + "ff";  
 row.style.backgroundColor = "#" + bgcolorValue;  
 if(down && (bgcolor-steps) > 0){ //if subtracting, prevent negatives  
   bgcolor = (bgcolor - steps);  
 }else{ bgcolor = (bgcolor + steps);  
   down = false;  
 } if(bgcolor > 255){ //prevent too high values  
   bgcolor = (bgcolor - steps);  
   down = true;  
 }  
}

Since the colors are being calculated, we need to make sure that we don’t go out of range, Valid values are from 0 to 255. The color argument is not separated into RGB values, so we need to pad if we go below 16, otherwise, the value will be illegal. If we have a really long table or a big steps value, the gradient will turn in the other direction. In this function, the blue part is fixed and the other two are modified.

The toString method is quite handy when you need to convert numbers — decimal to hex, in this case. The argument in toString is the radix, ie. 2 for binary, 10 for decimal, and 16 for hex. The image below shows how the table appears in Results in Firefox 1.0, IE6, Mozilla 1.7 and Opera 7.5.

1457_rowcolor3

Take care not to make the display too colorful — we still want to ensure the readability of our tabular data. With some color combinations, it might even be necessary to change the color of the table text using something like this:

if(color < switchingPoint){   
 row.style.color = "white";  
}else{  
 row.style.color = "black";  
}
Conclusion

Using CSS and JavaScript, it’s fairly easy to add or increase the readability of our code without having to regenerate the HTML page from a server application. As we’ve seen here, it can also be added on static HTML pages. To see these examples in action, download the HTML file containing the code.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Vijay

    Thank you for the great article. Really appreciate it and its what I was looking for.
    I had one question. This technique where we change the background color of table rows, it works only when we fire the command from the combo box change event. Is there a way to do this without such a event. The table rows to have the colors on loading the page?

    Thanks in advance :)

    • Kennet Svanberg

      Look for the text in the article : “The above function should be called from the onload event of the body tag:” there is the description on how to load the function when the document is loaded.