Alternating Colors Using 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>&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

This site runs on the Thesis WordPress Theme

Thesis Theme thumbnail

If you're someone who doesn't understand a lot of PHP, HTML, or CSS, Thesis will give you a ton of functionality without having to alter any code. For the advanced, Thesis has incredible customization possibilities via extensive hooks and filters. And with so many design options, you can use the template over and over and never have it look like the same site.

If you're more familiar with how websites work, you can use the fantastic Thesis User's Guide and world-class support forums to make more professional customizations than you ever thought possible. The theme is not only highly customizable, but it allows me to build sites with a much more targeted focus on monetization than ever before. You can find out more about Thesis below:

Leave a Comment

Previous post:

Next post: