Help to color-alternate rows in sortable table

I'm using jQuery tablesorter plugin. I'm relatively new to jQuery and need help from jQuery ninjas.

My table has color-alternative rows. I used CSS nth-child() to alternate the rows.

table.tablesorter tbody tr:nth-child(odd) td {
    background-color:#FBFBFB;
}

It works fine in Chrome and Firefox but IE doesn't like it. IE doesn't support nth-child.

I tried to control color-alternating with JavaScript when page loads.

$(document).ready(function() {
  $('#packageTbl').tablesorter();
  $('table.tablesorter tbody tr:nth-child(odd) td').css('background-color', '#FBFBFB');
  $('table.tablesorter tbody tr:nth-child(even) td').css('background-color', '#DDD');
});

And it works fine when the page originally loads but when I click on a column to sort, my color-alternative rows do not alternate any more. I might have two white rows then three gray ones.

Can you suggest any solution that can help me.

Answers:

Answer

Tablesorter has a built in function to "zebra" stripe the rows, it also automatically updates the striping after sorting. Use it as follows:

CSS

.NormRow { background-color: #fbfbfb; }
.AltRow  { background-color: #ddd; }

Script

$('#packageTbl').tablesorter({
   widgets: ['zebra'],
   widgetZebra: {css: ["NormRow","AltRow"]} // css classes to apply to rows
});

Update: Actually, the default CSS the tablesorter uses is "odd" and "even" so change the css names to that if you wish.

Answer

JavaScript:

$('.tablesorter tr:nth-child(odd)').addClass('odd');

CSS:

.odd {
    background-color:#FBFBFB;
}

Example can be found here.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.