Alternating Row Colors Using Only JavaScript
Apr
05
Below is a JavaScript that will make alternating the row colors of a table extremely simple. The beauty of it is that the script is only 16 lines long!
function
alternateRowColor(tableid,lightclass,darkclass,overclass)
{
var tableid =
document.getElementById(tableid);
var rows =
tableid.tBodies[0].rows;
for(var ii = 0; ii < rows.length;
ii++) {
var row =
rows[ii];
if(ii % 2)
{
row.className =
lightclass;
row.onmouseover = function ()
{overRow(this.id,overclass);};
row.onmouseout = function ()
{overRow(this.id,lightclass);};
} else
{
&nb
sp; row.className = darkclass;
&nb
sp; row.onmouseover = function ()
{overRow(this.id,overclass);};
&nb
sp; row.onmouseout = function ()
{overRow(this.id,darkclass);};
}
}
}
I've added a nice little row highlighting function to the
mouseover and mouseout events called
overRow(). This function only
adds 3 lines of code:
function overRow(rowid, classname) {
document.getElementById(rowid).clas
sName = classname;
}
The last thing to do is make sure that the
alternateRowColor() function
gets invoked every time the page loads. Instead of having
to place this in the body tag of all pages, all
that is needed is one line of code added to the same script
that will automatically run the function each time a page
loads:
window.onload=function(){ alternateRowColor('alternateRows','light','dark','over');}
That's all there is to it. See it in action.

- Tagged as: No Tags
- Categorized under: CSS, JavaScript, Tutorials, Web Development
- Comments: 1 Comment »






