Easy Zebra Striping with Prototype
While reviewing some of the JQuery tutorials, I was impressed with the ease of setting up a table with alternating row colors.
This got me thinking that it should be a relatively easy thing to achieve using the Prototype library as well. In this edition, I will give quick example of doing just that.
We’ll start by using the element selector utility method ($$). This will return a list of the odd numbered rows in our table. We then add the oddRow classname to each of these matched table rows.
1 2 3 4 5 6 7 8 9 10 | function stripe(e) { var evens = $$('table.stripe tr:nth-child(odd)'); if(evens) { evens.each(function(tr) { tr.addClassName('oddRow'); }); } } Event.observe(window, 'load', stripe); |
The next step is to assign the stripe class to our table. Any table with this class will pick up the new behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <table class="stripe" border="0">
<thead>
<tr>
<th>Lorem</th>
<th>Ipsum</th>
<th>Dolor</th>
<th>Sit</th>
<th>Amet</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lorem</td>
<td>Ipsum</td>
<td>Dolor</td>
<td>Sit</td>
<td>Amet</td>
</tr>
... |
Last step, we need to specify the CSS to change the background color. I also threw in a directive to collapse the borders.
1 2 3 4 5 6 | table.stripe tbody tr.oddRow { background-color: #eee; } table.stripe { border-collapse: collapse; } |
Here it is in action. Though it’s a bit crude it illustrates that the rows are highlighted as intended.
| Lorem | Ipsum | Dolor | Sit | Amet |
|---|---|---|---|---|
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
As always improvements, tweaks & suggestions are welcome.
