Alternating column colors with jQuery

By Tim Priebe on January 4, 2010 at 7:04 pm in Design, Technical, css, html

jquery-tablesWe recently had one of our designers create a table design for a client with alternating column colors. Instead of laughing at her and not coding it, we instead decided to use a little jQuery goodness to get it taken care of.

We included the following code in our document’s head, using the Google jQuery implementation:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");

google.setOnLoadCallback(function() {
$("table tr td:nth-child(even)").addClass("even-column");
$("table tr th:nth-child(even)").addClass("even-column");
});
</script>

So that’s the code that gives every other table cell, including header cells, the class of even-column. Now we can style those cells however we’d like.

In our case, a little CSS transformed the table pictured below on the left into the table on the right.

screen-shot-2010-01-04-at-64457-pm screen-shot-2010-01-04-at-64510-pm

Of course, putting the following in our google.setOnLoadCallback function will do something similar for rows.

$("table tr:nth-child(even) td").addClass("even-column");

This would result in the following:

screen-shot-2010-01-04-at-64554-pm

While this could have been solved by actually hard-coding the table’s cells with the even-column class, we are using Wordpress on this site. This means the client could add their own table on down the line, having no idea what a class is, much less to add a specific one to every other cell in every row of the table. Plus, that would be a lot of work.