Striped tables using JavaScript
Share & bookmark this article
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:
| Product | Number in stock | Price |
|---|---|---|
| Webcredible uniform | 5 | £235 |
| Usability phaser | 2 | £43 |
| Accessibility photon tracer | 3 | £72 |
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 <body onload="callfunction()"> 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
Advert: Training courses
Come on one of our training courses and become a web guru! Our 15 courses are run across 5 training streams:
- Usability & accessibility courses
- Website optimisation courses
- Online copywriting courses
- Web development courses
- Online marketing courses
Training courses are held every 2 weeks in London and are fantastic - small class sizes, highly interactive and taught by experts.
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.
Check out this fully functioning example.
This article was written by Paul McCarthy. Paul's crazy about CSS and using JavaScript for good (not evil) - so crazy that he works for Webcredible, an industry-leading user experience consultancy, helping to make the Internet a better place for everyone. He loves spending his time working on the world's most accessible CMS and is very good at CSS training.
What next?
- Read more web development articles on this website
- Get a highly accessible CSS website through our accessible CSS web design expertise
- Get our accessible and usable CMS so your site offers outstanding accessibility
- Attend our interactive intermediate CSS training, advanced CSS training and jQuery training courses
