Alternating Colors Using Prototype

by Terri Ann on January 31, 2008

This entry is part 5 of 10 in the series Prototype Tutorial

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>&amp; 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

Pages: 1 2

Leave a Comment

Previous post:

Next post: