leora
leora

Reputation: 196539

How can I alternate "visible" rows in an html table using jQuery

I have this code that does alternating rows for a html in jQuery:

function AlternateRowColors() {

    $("table.altRow1 tr").filter(function() { 
    return true;
    }).filter(':even').addClass('alt'​​​​​​);

    $("tr.alt td[rowspan]").each(function() {
    $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
    });

    $('ins').css("background-color", "#cfc")
}

This works great (feel free to add suggestions if anything is inefficient above).

The issue that I have now is that I have code that hides a bunch of rows (details on why are not really relevant for this question), the main point is that I want to have a function that can do alternative row colors to current visible rows.

I am hiding rows by simply adding a class to certain rows and them calling .hide() on that class.

Is there any suggestion to get alternative row colors (like the above code) but have it work on the visible rows so no matter what is hidden, the table always looks correct in terms of alt row coloring.

Upvotes: 5

Views: 3085

Answers (4)

Stonedecroze
Stonedecroze

Reputation: 58

Chain the selection:

$('table tr:visible:even').addClass('alt');

Upvotes: -1

leora
leora

Reputation: 196539

i wound up using this which seemed to work:

function UpdateTable() {
$('table.altRow1 tr:visible').removeClass('odd').filter(':odd').addClass('odd');

with this css:

.altRow1 tr {
     background-color: #FFFFFF;
 }
 .altRow1 tr.odd {
     background-color: #DEDEDE;
 }

Upvotes: 8

Robbert
Robbert

Reputation: 713

You might want to call this function again when you are hiding rows, so that it can re-calculate odd and even rows. You can use the not-selector on your tablerows to get only the visible rows, like this:

$('table.altRow1 tr:not(.hidden)') 

Upvotes: 1

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

I would suggest that you add a class to the visible rows as well in the code that you have to add the class to hidden rows. Say you add the class named visible. Then you can apply your alternating rows code above to the class visible:

 $("table.altRow1 tr.visible").filter(function() { 

and so on.

Upvotes: 1

Related Questions