Five Ways to Spice Up Your Site with jQuery
By Akash Mehta2008-11-05
If you're displaying a lot of data in your table, chances are your users are finding it quite tricky to scan and understand it. An easy improvement on this is table striping - alternating a background color for each row. However, table striping is typically quite messy, with a class on every row. If you use static HTML, moving rows around can break the continuity; if you use a server-side scripting language, you can end up with messes like this:

The main problem is this: there is no reliable way to select
alternate rows in CSS, purely on the client side. jQuery, however,
provides excellent CSS support and has a handy little :even selector we can use for exactly this. Let's say we have the following table:
| Flight Number | From | To | Departure | Arrival |
|---|---|---|---|---|
| BA 3451 | Heathrow | Nuremberg | 19:20 | 19:50 |
| BA 1254 | Luton | Alicante | 19:40 | 20:50 |
| LH 331 | Heathrow | Hamburg | 20:00 | 20:20 |
We're using the following code:
<table id="flight_table">
<thead>
<tr>
<th>Flight Number</th>
...
</tr>
</thead>
<tbody>
<tr>
<td>BA 3451</td>
...
</tr>
</tbody>
</table>
Using <tbody>, we can select only the data rows
of the table. We then need to use our even selector from before to
select these rows, and apply a background color:
$("#flight_table tbody tr:even").css("background-color","#ddd");
Better still, we can apply a class to the alternate rows
dynamically. As the class is loaded on the client side, we don't have
to change all our HTML or mess around with templates when we update the
table. Also, chances are you don't currently use <thead> and <tbody> - we can replace these with a jQuery filter as well! Assuming your header row is your first row, the :first
selector is perfectly sufficient for only applying our styles to the
actual body of the table, leaving your table header styling intact.
Here's the code:
$("table tr").not(":first").filter(":even").addClass("altrow")
You can then easily style these in your CSS:
tr.altrow { background-color: #eee; }
Here's the final result:

Tutorial pages:
|
|
|||||||||
You might also want to check these out:
|
Link to This Tutorial Page!

