Striped Tables Using JavaScript

by: Paul McCarthy

Introduction

JavaScript can be incredibly useful when you need to automate repetitive tasks. In this article we'll implement a simple JavaScript function that will apply alternate striped rows to a table.

We'll implement this technique using unobtrusive JavaScript.

Resources for the striped tables tutorial

Download the required resources before beginning this tutorial.

Start by opening the file 'striped-tables-example.htm'. This is the table we're going to add stripes to using JavaScript:


Rather than applying a class to every other row to assign the alternate background rows, we can let JavaScript do the work for us.

The JavaScript

So you can see what we're aiming to do, check out this fully functioning example.

Open the 'js.js' file you've downloaded and let's get started!

Registering an event

The first task is to create an event that occurs when the page has loaded. Rather than trying to execute a function call using within the HTML page we're going to use Simon Willison's addLoadEvent(func). This will allow us to add function calls once the page has loaded.

Type the following JavaScript into the .js file:

function addLoadEvent(func)
{
    var oldonload = window.onload;

    if (typeof window.onload != 'function')
   {
       window.onload = func;
   } else {
        window.onload = function()
           {
              oldonload();
              func();
            }
    }
}
addLoadEvent(fgetAllDataTables);

Collecting table elements

Create an empty function in your JavaScript file called fgetAllDataTables. To avoid any JavaScript errors with the script, check to see if the command getElementsByTagName is available:

function fgetAllDataTables()
{
   if (!document.getElementsByTagName)
  return false;
}

The second task is to create collections of the table elements that will be manipulated by the JavaScript. Use the getElementsByTagName command to retrieve all the tables. Next assign all tables to the variable eleTables, as follows:

function fgetAllDataTables()
{
   if (!document.getElementsByTagName) return false;
   var eleTables = document.getElementsByTagName("table");
}

Looping through tables

All tables have been assigned to the variable eleTables as an HTML object collection. The next step is to loop through all the tables and check to see if a class of datatable, class="datatable", has been assigned to any of them.

function fgetAllDataTables()
{
  if (!document.getElementsByTagName) return false;

  var eleTables = document.getElementsByTagName("table");
  for (var i=0; i < eleTables.length; i++)
 {
    if (eleTables[i].className == "datatable")
   {
    }
  }
}

The fgetAllDataTables() function is almost complete. Our next task is to apply the stripes to the tables with a class of datatable, class="datatable". We'll do this by passing any tables with this class to a new function called fStripes, as follows:

function fgetAllDataTables()
{
  if (!document.getElementsByTagName) return false;

  var eleTables = document.getElementsByTagName("table");
  for (var i=0; i < eleTables.length; i++) {
    if (eleTables[i].className == "datatable")
    {
         fStripes(eleTables[i]);
     }
  }
}

Striped rows

We've passed the fStripes function any tables that need to be made stripey. Create an empty function called fStripes:

function fStripes(eleTable)
{
}

Every other row requires a class of trgrey applied to it. The class has been predefined in an external stylesheet:

.trbg
{
 background: #eee;
}

First create a loop based on the number of rows contained by the table. Then apply the class to every other row starting from 1, as follows:

function fStripes(eleTable)
{
  var eleTableRows = eleTable.getElementsByTagName("tr");
  for (var i=1; i < eleTableRows.length; i++)
 {
    eleTableRows[i].className = "trbg";
    i++;
  }
}



Benefits of JavaScript striped tables

JavaScript can be used to simplify repetitive tasks. Rather than applying a class to every other row a single class is applied to the table itself.

This technique is extremely useful in content managed environments. Content editors may not have the time or expertise to reliably apply classes deep within the HTML. Applying the single class to a high level HTML element and using JavaScript to present its children can help keep a site visually consistent and improve its maintainability.



Article published Wednesday, 23rd January 2008
© 2008 NetVisits, Inc. All rights reserved.