Question

I have a table with 'zebra stripes' which adds a class to every second, or 'even', <tr>, eg:

 $("#summarytable tr:even").addClass("even");

I am also using the Table Sorter plugin which allows the sorting columns alphabetically and numerically if a <th> is clicked.

The problem is that 'even' <tr>s remain 'even' even after they've been sorted by the plugin and their order shuffled. So, even if I remove and then add the '.even' class again, eg:

$("#summarytable th").click(function() {
    $("#summarytable tr").removeClass("even");
    $("#summarytable tr:even").addClass("even");
});

It still appears out of order.

Is there someway to 'reset' the order of elements in the DOM and thus reset an elements 'odd' or 'even' status?

Dev example here: http://ryanturner.com.au/tipping/index.php?id=4

Was it helpful?

Solution

If the striping is only for styling, you can sidestep this whole problem just using CSS.

Example:

tr:nth-child(2n) {
    background: gray;
}
tr:nth-child(2n+1) {
    background: lightgray;
}

If you really need some function to run after sorting takes place, a quick glance at the documentation suggests that you might do it like this:

$("table").bind("sortEnd", function() { 
    // ...
}); 

OTHER TIPS

Why are you using jQuery for something that's easily achievable with CSS?

#summarytable tr:nth-child(even) {
    /* your styles here */
}

This will update automatically, no matter what happens. Even if the user decides to go into the DOM Inspector and start deleting table rows from the DOM, they will still update automatically and look beautiful.

Coming from Table Sorter docs, there is a module called Zebra, which adds the relevant classes. You use it like this:

$("table").tablesorter({
  widgets: ["zebra"],
  // change the default striping class names
  widgetOptions : {
    zebra : [ "normal-row", "alt-row" ]
  }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top