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.
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.
Last step, we need to specify the CSS to change the background color. I also threw in a directive to collapse the borders.
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 |
| Lorem | Ipsum | Dolor | Sit | Amet |
| Lorem | Ipsum | Dolor | Sit | Amet |
As always improvements, tweaks & suggestions are welcome.
