Moja Ra Moja Ra - 1 month ago 9
jQuery Question

How do I sort my table and keep alternating background colors while sorting using jquery?

I am having a problem with my table rows background colors once I start sorting columns. When my document loads the code is runs like this:

$('tbody tr:even').css('background-color','#F1F1F1');
$('tbody tr:odd').css('background-color','#FFFFF0');


The code to sort my th is this:

$('.toggle').toggle(function(){
$(this).css("background-image", "url('desc.gif')");
}, function(){
$(this).css("background-image", "url('asc.gif')");
});


but once they start sorting there are even rows right on top of each other and odd rows on top of each other. What can I right to alternate row color when sorting? I have already tried the following and it does not work:

$('.toggle').toggle(function(){
$(this).css("background-image", "url('desc.gif')");
$('tbody tr:even').css('background-color','#F1F1F1');
$('tbody tr:odd').css('background-color','#FFFFF0');
}, function(){
$(this).css("background-image", "url('asc.gif')");
$('tbody tr:even').css('background-color','#F1F1F1');
$('tbody tr:odd').css('background-color','#FFFFF0');
});

Answer

You can get sorting and zebra striping out-of-the-box if you just use jQuery Tablesorter. I use it all the time, it works great.

An example of a table set up with sorting that maintains the proper alternating row colours would be:

$("#mytable").tablesorter({
  widgets: ['zebra']
});