A List Apart


The Table Ruler

Before the days of digital documents and OCR scanning, data entry was a tedious process involving much typing and squinting. You would be handed a huge printout, and asked to type its contents line by tiring line. If you became bored or distracted for even a moment, you could easily lose your place.

Article Continues Below

But you were clever. You got hold of a big old metal ruler, placed it on top of the printout, and moved it down each time you finished typing a row, to remind you where you were and what you had already typed.

One ruler to help us not get stuck

With a bit of JavaScript / DOM sorcery, we can provide our visitors with the same functionality for long data tables in HTML, by applying rollover states to the rows. This could be implemented tediously by hand, of course, but it would be silly to do so. Instead, we will use the DOM to find the rows to highlight on mouseover.

Before we proceed, see the effect in action.

Meet the markup

To avoid the script highlighting every table in the document, we need to tell it which tables to add the ruler to and which not to. We do this by giving the tables in question a class with the name “ruler.” Next thing we need to avoid is rows in the table header and the table footer to be highlighted.

Let’s take a look at a demo table:

<table class="ruler" summary="Table of my records">
<caption>My Records</caption>
    <th scope="col">Artist</th>
    <th scope="col">Title</th>
    [... more content rows here ....]</tbody>
    <td colspan="2">Last updated: 17.03.2004</td>

And the script to apply the ruler:

function tableruler()
 if (document.getElementById &&» 
   var tables=document.getElementsByTagName»
   for (var i=0;i<tables.length;i++)
     var trs=tables.getElementsByTagName('tr');
     for(var j=0;j<trs.length;j++)
       && trs[j].parentNode.nodeName!='TFOOT')
        className='ruled';return false}
        className='';return false}

First, we check to see if the browser supports the DOM; then we get all tables in the document, and loop through them.

We check to see if the name of the table class is “ruler.” If it isn’t, we skip it and proceed to the next table.

If it is, we take all the table rows and loop through them.

We check to see if the node above the current one is a TBODY (not a TFOOT or THEAD); if it is, we apply a function on mouseover that changes the row’s class name to “ruled.”

Then we wipe the class name clean on mouse-out.

Styling the ruler

To control the effect, all you need to define in your style sheet is a class for the ruler:


These settings will be applied to every highlighted row inside every table with the class “ruler.”

If you want to have different rulers for different tables, simply give the table an ID:

<table class="ruler" id="mytable" summary="Table of my records">

and in the CSS:

#mytable tr.ruled{

That’s all there is to it. May your rule be long and happy.

97 Reader Comments

Load Comments