Thursday, January 7, 2010

Alternate Table Rows Color

Let's start with an ordinary html table. Whether the table contains head/foot elements doesn't matter in this case:
           
0 - some txt
1 - some txt
2 - some txt
3 - some txt
4 - some txt

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:

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:





0 comments:

Post a Comment

Don't forget to leave your comment about this post.
It will help us to improve this blog.

blogger templates | Make Money Online