Monday 6 July 2009

jQuery Zebra Highlighting for Tables

Cheers Tom for the driving lesson.

For my dissertation I used a number of tables to illustrate the modules on offer and some normalization. In order to make 'em a little less boring I used different classes for alterate rows... which was tedious to say the least. Then I came across the Zebra Widget for TableSorter, a rather cool jQuery plugin.

This was easy to include and added the benefit of allowing me to sort the data in the table by using the tablesorter functions... it might have been easier to just have the zebra highlighting but I wasn't sure if I'd ever need the facility of sorting the data... couldn't hurt now could it?

Anyway, to get it working I placed this in the head:

    <script type="text/javascript" src="../js/jquery-1.2.3.min.js">
    </script>
    <script type="text/javascript" src="../js/jquery.tablesorter.min.js">
    </script>
    <script type="text/javascript">
      $(function(){
        $("table").tablesorter({widgets: ['zebra']});
      });
    </script>

Of course, if you've a number of tables on your page you can use the power of jQuery selectors to be a bit more choosey about which one/s you choose to have the script work on... I just had the one table on the page so just used "table".

Along with the script inclusion above you'll also need to alter your CSS to something like:

tr.odd{
 background-color:      #999999;
}

This'll allow the script/widget/plugin to alter the appearance of your rows... of course it means that the default background-color of the rows will have to be something other than gray 60 wink.

No comments:

Post a Comment