jQuery Stripe Thy Tables

Tiger Stripes

So what we want is to apply style to alternate rows in our table. I’m going to use the jQuery :even custom selector to achieve this. This is simple yet very useful.

The Markup

First, let’s start off with a simple accessible table.

<table summary=“Superheros from the X-Men and their powers”>
<caption>X-Men</caption>
<tr>
<th>Superhero</th>
<th>Power</th>
</tr>
<tr>
<td>Cyclops</td>
<td>produces optic blast</td>
</tr>
<tr>
<td>Iceman</td>
<td>cryokinesis</td>
</tr>
<tr>
<td>Storm</td>
<td>weather control</td>
</tr>
<tr>
<td>Wolverine</td>
<td>healing factor</td>
</tr>
</table>

The Style

Next, let’s add a little CSS.

.even { background-color:#eee; }

The even class is all the style you need to display the striping, but I’m going to add some more CSS to make the table look cool.

table { border-collapse:collapse;width:525px; } caption { margin-bottom:10px; } th { background-color:#ddd; } th, td { border:1px solid #ccc;padding:15px; }

The jQuery

Finally, a few lines of jQuery.

$(function() { $(‘tr:even’).addClass(‘even’); });

That’s it, good to go! Thy table now has stripes.

X-Men
Superhero Power
Cyclops produces optic blast
Iceman cryokinesis
Storm weather control
Wolverine healing factor

8 Responses

  1. Tim says:

    Great tip. How about a non-table layout?

  2. Steven says:

    The jQuery :even selector can be used on other elements also, not just tables. Thanks for the reply!

  3. Neo says:

    Awesome tips dude.

  4. Steven says:

    Neo, you are the one. Thanks dude!

  5. charles xavier says:

    Awesome find & excellent for data tables. I’m doing a SharePoint site for “MY QUEENS!!!!” and we need to dynamically alter row styling. this will come in handy. Thanks homie!

  6. Steven says:

    Thanks Professor Xavier and you’re a pimp btw. Haha, My Queen – 300! Yep, this should work nice with SharePoint tables. Appreciate the good feedback bro!

  7. charles xavier says:

    HAHAHA!
    like how you re-did the table with my cronies.

  8. Steven says:

    Indeed professor! Tell Jean Grey hi for me. Cheers!

Leave a Reply

(required)