Alternate rows with jQuery (Tiger / Zebra Stripes)

February 14, 2008

It’s always been a pain to add alternate styles to table rows, lists etc. With jQuery you can do this easily, you can even make it apply globally to you site.

Example:

<html>
<head>
<title>Alternating Rows with jQuery</title>
<style type="text/css">
table {width:400px; border:1px solid blue;}
.oddrow {background-color:#E5E5E5;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function(){
  $("table.tiger-stripe tr:even").addClass("oddrow");
});
</script>
</head>
<body>

<table class="tiger-stripe">
  <caption>Alternating Rows with jQuery</caption>
  <tr>
    <td>Row 1</td>
  </tr>
  <tr>
    <td>Row 2</td>
  </tr>
  <tr>
    <td>Row 3</td>
  </tr>
  <tr>
    <td>Row 4</td>
  </tr>
</table>

</body>
</html>

The javascript code used in the example above means that any tables that have a class of "tiger-stripe" will have have the class "oddrow" applied to every other row. It is worth noting that jQuery (and Javascript) starts counting from zero. So, the above example will apply the oddrow class to the 1st, 3rd, 5th, etc rows.

If you want to do it all with server side code to be ultra-accessible then in ColdFusion you can do something like this:

<table>
<cfloop query="myQuery">
  <tr class="<cfif currentrow MOD 2>evenrow<cfelse>oddrow</cfif>">
    <td>...</td>
  </tr>
</cfloop>
</table>

 


6 comments

  1. i would be nice to see a working example of the jquery method as i can not seem to get it to work. Seeing the code in context would also be helpful.

    Comment by Howard Ross – June 20, 2008
  2. Hi Howard,
    I've updated the post to include a working example. I hope that helps :)

    Comment by John Whish – June 20, 2008
  3. Wow, thanks for speedy response. That is very helpful

    Comment by Howard Ross – June 20, 2008
  4. Wow, thanks for speedy response. That is very helpful

    Comment by Howard Ross – June 20, 2008
  5. @Howard - no problem, glad I could help. We've all had those moments when we just needed a good example!

    Comment by John Whish – June 20, 2008
  6. nice script, thanks

    Comment by Bilard – December 12, 2008

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.