views:

1747

answers:

3

i took an html table that i am applying alternative row colors and i just added jquery table sorter on it so users can sort the table.

the issue is that the alternative row colors are all messed up now as (based on the sorting) there are multiple rows with the same backcolor . .

is there anyway to reset the alternative row color with jquery table sorter?

+1  A: 

How about:

function fixStripes() {
     var i = 0;
     var rowclass;
     $("table tr").each(function() {
          $(this).removeClass("odd even");
          rowclass = (i%2 == 1) ? "odd" : "even";
          $(this).addClass(rowClass);
      });
}

$("table").bind("sort", fixStripes);

Oh, and if you want a really simple fix, you could hold your breath for this CSS pseudo-class to get picked up by all the major browsers:

table tr:nth-child(n+1) {
    color: #ccc;
}

But my guess is based on how FF and company handle CSS for dynamic HTML, it would set your stripes onload, but not apply the CSS after you sort. But I'd like to know for sure.

Anthony
Think you also need `$(this).removeClass('odd even')` to make sure each row gets reset correctly.
dcrosta
I just realized that! I'm back for edits. good lookin out.
Anthony
+3  A: 

Based on Anthony's answer, but rephrased as a one-liner (mostly):

function fixStripes() {
    $('table tr').removeClass('odd even')
        .filter(':even').addClass('even').end()
        .filter(':odd').addClass('odd');
}

$("table").bind("sort", fixStripes);

JQuery calls can be "chained" as above, using operations like filter() to limit the selected elements, and .end() to "reset" to the last selection. Put another way, each .end() "undoes" the previous .filter(). The final .end() is left off, since there's nothing to do after that.

dcrosta
That should be `$('table tr')`
Anthony
Quite right, thanks for the catch.
dcrosta
BTW, tablesorter now seems to call sortStart and sortEnd rather than just sort.
Xiong Chiamiov
+7  A: 

There's already a default widget zebra, built into the core, which applies the classes odd and even to alternate rows. It works whether or not you have added class=even/odd to the html file.

It's really easy to set up. I simply followed the instructions on the table sorter website, and then modified the document ready function to the following:

<script type="text/javascript">
$(document).ready(function() 
    { 
        $("#myTable").tablesorter({ 
    widgets: ['zebra'] 
    }); 
    } 
); 
</script>

To prove that it's easy to set up, here's what I made while I was trying to answer your question. I've also zipped all the code into one file. I used the Blue Skin theme that you can download from the tablesorter website.

Alasdair