Alternating Colors Using Prototype
- Simple Hide and Show with Prototype
- Event Observe and Event Listeners with Prototype
- JavaScript Script.aculo.us Fade with a Timer
- Evolving Styles: Add, Change Remove Classes with Prototype
- Alternating Colors Using Prototype
- First, Last, Active and Only List Styles With Prototype
- Change Rel External to Target Blank using Prototype
- Zip Code, Phone Number and Replacing Empty Fields with Really Easy Validation
- Limit Characters in a Textarea with Prototype
- Open Links to a Different Site in a New Window with Prototype
Learned a cool new Prototype trick the other day, it's really easy to alternate the coloring of rows with JavaScript and CSS.
I just create a simple table to alternate different colors for the even and odd rows. The only class or id I need is the id for the table, in this case evenodd, Prototype is going to handle choosing and applying classes to the alternate lines for us!
HTML
<table id="evenodd">
<thead>
<tr>
<th>Even</th>
<th>& Odd</th>
<th>Alternate</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lorem</td>
<td>ipsum</td>
<td>dolor</td>
</tr>
<tr>
<td>sit</td>
<td>amet</td>
<td>consectetuer</td>
</tr>
<tr>
<td>adipiscing</td>
<td>elit</td>
<td>Phasellus</td>
<tr>
<td>Lorem</td>
<td>ipsum</td>
<td>dolor</td>
</tr>
</tbody>
</table>
Equip with two classes even and odd:
CSS
.odd {background-color: #F9D8A2;}
.even {background-color: #FFF6E5;}
And a tiny bit of JavaScript (Oh and don't forget Prototype):
JavaScript
Event.observe(window, 'load', function() {
$$('table#evenodd tbody > tr:nth-child(odd)').each(function(s) {
s.addClassName('odd');
});
$$('table#evenodd tbody > tr:nth-child(even)').each(function(s) {
s.addClassName('even');
});
});
Check out the alternating table row colors demo.
And now the even rows within the <tbody> have the class even applied to them and vice-versa with the odd rows. It's important to use the <tbody> tag to designate the body content of the table and to keep it separate from the head(<thead>) and the foot(<tfoot>) as well as the caption(<caption>) of the table.
Never before have I used this nth-child() CSS selector, so I did some research into it in the W3C Documentation
Continue on to page 2: Use 5 alternating colors by just changing the nth selector
the newest discoveries, stories and shared tips!Come on, all the cool kids are doing it ;)


