Assigning Background Colors Dynamically to Zebra Tables with CSS and JavaScript - Building zebra tables dynamically with a JavaScript function
(Page 3 of 4 )
Throughout the course of the previous section, I mentioned the possibility of using a pinch of JavaScript to dynamically generate the alternate background colors of even and odd rows contained in a specific table. This will achieve the characteristic zebra appearance without having to manually include the pertinent CSS classes into the markup.
Based on this premise, I’m going to define a short JavaScript function that will be responsible for iterating over the even and odd rows of a determined (X)HTML table, and then alternate their respective background colors.
Want to see how this brand new JavaScript function looks? Here is its simple signature:
function buildZebraTable(tableId){
var table=document.getElementById(tableId);
if(!table){return};
var evenFlag=false;
var rows=document.getElementsByTagName('tr');
for(var i=0;i<rows.length;i++){
rows[i].className=!evenFlag?'oddrow':'evenrow';
evenFlag=!evenFlag;
}
}
As you can see, the logic implemented by the above “buildZebraTable()” JavaSCript function is quite simple to follow. Essentially, all that this function does is iterate over the rows of a specified (X)HTML table, and alternately style each of them via the assignment of two CSS classes, called “oddrow” and “evenrow” respectively. Obviously, the immediate result of this process, assuming that the pertinent CSS classes define different background colors, is the dynamic creation of a zebra table using only a short JavaScript function.
Moreover, the previous “buildZebraTable()” function should be called after the target table has been loaded in the following way:
window.onload=function(){
if(document.getElementById&&document.
getElementsByTagName&&document.createElement){
buildZebraTable('zebratable');
}
}
Building a zebra table with the help of JavaScript is a simple, yet effective process that only requires defining a function similar to the one that you learned earlier. However, once you've grasped the logic that stands behind this approach, it’d be more than desirable to put the mentioned JavaScript function, the CSS styles, and the markup of a sample (X)HTML table all together in one single file so you can see how they link with each other.
Keeping this in mind, in the last section of this tutorial I’m going to build such a file, thus completing my demonstration of how to construct zebra tables through the proper combination of some basic CSS styles and a JavaScript function.
To see the full definition of this (x)HTML file, please jump ahead and read the next few lines. We’re almost finished!
Next: Setting up a final hands-on example >>
More JavaScript Articles
More By Alejandro Gervasio