Using Javascript for Coloring Table Rows

Dec 04, 2006

I think it’s pretty safe to say that alternating the color of the rows in a table is a big plus for usability. This especially true in tables that span multiple columns and end up being fairly wide. It’s just one of those simple things you can do to make your users happy (and they probably won’t even realize it).

With Rails a common approach has been to do something like this:

<% i = 0 %>
<table>
  <% for each object in @objects %>
  <tr class="line<%= i %>">
    <td><%= object.attribute %></td>
  </tr>
  <% i = 1-i %>
  <% end %>
</table>

This will give alternating rows with a class of line0 or line1, which you then can set a background color appropriately using a stylesheet. The problem with this method, which I recently ran into, is when your table is composed of multiple partials. Suddenly to have to keep track of your counter across multiple partials and it just gets messy after awhile. A less troublesome solution is to color the rows of your table after it has been rendered with javascript.

The Javascript:

window.onload=function()
{    
  var b, r, t = document.getElementsByTagName("TABLE");
    for(var i=0; i<t.length; i++)
    {    
      var current_t = t[i];
        b = current_t.getElementsByTagName("TBODY");
        for(var j=0; j<b.length; j++)
        {    
          var current_b = b[j];
            r = current_b.getElementsByTagName("TR");
            for(var k=1; k<r.length; k+=2)
            {    
              r[k].className = "line1";
            }
        }
    }
}
The Table:
<table>
<tbody>
  <% for object in @objects %>
  <tr>
    <td><%= object.attribute %></td>
  </tr>
  <% end %>
</tbody>
</table>

The purpose of the <tbody> tags is so that you can encapsulate any header rows in <thead> tags and still only have your body rows colored by the javascript. This method ends up being reasonably easy to implement and results in cleaner markup in your views.