Get fancy striped tables by just writing one extra line of code

 

For the past few weeks or so I have been experimenting with the wonderful jQuery javascript library and I must say I am in love with it. Given that I need something to write about on this blog and feel the need to pass on the wonder of jQuery to the world, I thought I would give a quick little tutorial on how to get striped tables using jQuery.

This will be our final product.

stripes.jpg

We will start out with just our html which will be this.

<table class='highlight'>
<tr>
<td>13</td>
<td>John Doe</td>
<td>555 43th Street</td>
<td>New York</td>
<td>New York</td>
</tr>
<tr>
<td>14</td>
<td>Jane Doe</td>
<td>4332 Main Street</td>
<td>Canton</td>
<td>Ohio</td>
</tr>
<tr>
<td>15</td>
<td>Joe Doe</td>
<td>5345 Bradley Drive</td>
<td>Chicago</td>
<td>Ohio</td>
</tr>
<tr>
<td>16</td>
<td>Jill Doe</td>
<td>34 Main St.</td>
<td>Virginia Beach</td>
<td>Virginia</td>
</tr>
</table>

Alright, there is really only one main thing that I need to point out about this code and that is the class that is declared in the table tag. All this class does is collapse the border of the table so the row is continuous. That class contains the following code.

table.highlight
{
border-collapse: collapse;
}

Alright, now to the reason why you are here. Striped tables! With jQuery doing this is ridiculously simply, I mean so simply its crazy. The code to get the striped table is this and adding the jQuery library of course.

$(document).ready(function(){
$(”tr:even”).addClass(”highlight”);
});

Yup, its that simple. Let me break it down a little. $(document).ready(function(){ is jQuery’s way of saying don’t do this javascript until the page has loaded and is ready. This is the beginning of pretty much anything you do with jQuery. The second is where the magin happens. $("tr:even").addClass("highlight"); will look for all tr elements in a document. It will count, starting at zero, how many tr elements there are and add the highlight class to the even numbered elements. If we look at the table image we see that the zero and second row, or even, rows are have the highlighted class applied to them.

stripes.jpg

The highlight class

tr.hightlight{
background-color:#38610B;
color: #FFC;
}

So thats all there is. If you would like all the odd rows to have the class then replace even with odd. There are multiple other things you can find using jQuery to manipulate your web pages. Below are some of the thinks that will help learning more about jQuery.

jQuery.com
jQuery Tutorials
How to Get Anything You Want
Learning jQuery

Well, I hope this tutorial helped you out. Let me know what you thought about it. If you want the files to see how this works a little better leave your email in the comments and I will send you a zip with what you would need

Leave a Reply