Advanced Row Striping
As we saw earlier in the chapter, row striping can be as simple as two lines of code to alternate the background color:
$(document).ready(function() { $('table.sortable tbody tr:odd').addClass('odd'); $('table.sortable tbody tr:even').addClass('even'); });
If we declare background colors for the odd
and even
classes as follows, we can see the rows in alternating shades of gray:
tr.even { background-color: #eee; } tr.odd { background-color: #ddd; }
While this code works fine for simple table structures, if we introduce non-standard rows into the table, such as sub-headings, the basic odd-even pattern no longer suffices. For example, suppose we have a table of news items grouped by year, with columns for date, headline, author, and topic. One way to express this information is to wrap each year’s news items in a <tbody>
element and use <th colspan="4">
for the subheading. Such a table’s HTML (in abridged form) would look like this:
<table class="striped...