Learning jQuery - 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:
Sample Code
$(document).ready(function() {
$('table.sortable tbody tr:odd').addClass('odd')
$('table.sortable tbody tr:even').addClass('even')
})
Copyright exforsys.com
If we declare background colors for the odd and even classes as follows, we can see the rows in alternating shades of gray:
Sample Code
tr.even {
background-color: #eee
}
tr.odd {
background-color: #ddd
}
Copyright exforsys.com
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
element and use
|
for the subheading. Such a table's HTML (in abridged form) would look like this:
Sample Code
<table class="striped">
<thead>
<tr>
<th>Date</th>
<th>Headline</th>
<th>Author</th>
<th class="filter-column">Topic</th>
</tr>
</thead>
<tbody>
<tr>
<th colspan="4">2007</th>
</tr>
<tr>
<td>Mar 11</td>
<td>SXSWi jQuery Meetup</td>
<td>John Resig</td>
<td>conference</td>
</tr>
<tr>
<td>Feb 28</td>
<td>jQuery 1.1.2</td>
<td>John Resig</td>
<td>release</td>
</tr>
<tr>
<td>Feb 21</td>
<td>jQuery is OpenAjax Compliant</td>
<td>John Resig</td>
<td>standards</td>
</tr>
<tr>
<td>Feb 20</td>
<td>jQuery and Jack Slocum's Ext</td>
<td>John Resig</td>
<td>third-party</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4">2006</th>
</tr>
<tr>
<td>Dec 27</td>
<td>The Path to 1.1</td>
<td>John Resig</td>
<td>source</td>
</tr>
<tr>
<td>Dec 18</td>
<td>Meet The People Behind jQuery</td>
<td>John Resig</td>
<td>announcement</td>
</tr>
<tr>
<td>Dec 13</td>
<td>Helping you understand jQuery</td>
<td>John Resig</td>
<td>tutorial</td>
</tr>
</tbody>
<tbody>
<tr>
<th colspan="4">2005</th>
</tr>
<tr>
<td>Dec 17</td>
<td>JSON and RSS</td>
<td>John Resig</td>
<td>miscellaneous</td>
</tr>
</tbody>
</table>
Copyright exforsys.com
With separate CSS styles applied to
|
elements within
and
, a snippet of the table might look like this:
To ensure that the alternating gray rows do not override the color of the subheading rows, we need to adjust the selector expression:
Sample Code
$(document).ready(function() {
$('table.striped tbody tr:not([th]):odd').addClass('odd')
$('table.striped tbody tr:not([th]):even').addClass('even')
})
Copyright exforsys.com
The added selector, :not([th]), removes any table row that contains a
|
from the matched set of elements. Now the table will look like this:
