Striped tables using JavaScript

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

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.

Case studies

Our success stories

  • UCAS

    UCAS's Track portal is award-winning, achieving a 95%+ satisfaction rating across its 750,000 users

  • Hotels.com

    Hotels.com gained a much stronger competitive advantage due to a great mobile & tablet strategy

  • Pearson Education

    Pearson Education has embedded user-centred design into all their digital design processes

More case studies

What are you working on?

  • End-to-end customer experience

    Join up your customer touchpoints to deliver the best possible digital experience that is proven to deliver outstanding business results

  • Customer loyalty & retention

    Ensure your brand promises are delivered through your digital channels so that your customers return and bring others with them

  • User experience of digital touchpoints

    Make sure all your customer touchpoints consistently deliver the very best in user experience, design and usability.

  • Online sales & conversion optimisation

    Increase conversion across all your digital channels. Our clients sell more because they reap the benefits of our sales optimisation expertise.

  • Digital strategy

    Get ahead of the competition with a customer-centred digital strategy designed to deliver long-term business success.

  • Application & product design

    Deliver the best experience for your customers with intelligent digital applications tailored to your business goals and customer needs.

  • Mobile & tablet strategy

    Improve your mobile & tablet propositions with innovative, cutting-edge interface designs that work for you and your customers.

Webcredible turns 10

Happy Birthday to us

About us

We're a user experience agency (UX agency) that creates people-centred, efficient and delightful digital experiences.

Get in touch on 020 7423 6320

 

Skip to site navigation