leora leora - 7 months ago 8
HTML Question

How can you do alternative row color but just on visible rows?

I have the following code to do alternative row colors which works fine:

$("table.altRow tr:odd").css("background-color", "#DEDFDE");
$("table.altRow tr:even").css("background-color", "#EEECEE");


but i have certain cases where some rows are hidden so I wanted to see if there was any way to do alternative row colors but just apply to visible rows?

Answer
/**
 *  Iterate each visible row, if :odd or :even, apply 
 *  the relevant background colour depending on a flag.
**/
var evenOdd = 0;
$("table.altRow tr:visible").each(function() {  
    $(this).css("background-color", ( evenOdd ? "#DEDFDE" : "#EEECEE" ));
    evenOdd = !evenOdd;
});

Demo: http://jsfiddle.net/uMP5x/7/

As Andreas mentioned, you can use jQuery's .each()'s first arugment to your advantage with modulus, removing my initial need for a Boolean.

/**
 *  Iterate each visible row, if :odd or :even, apply 
 *  the relevant background colour depending if it's a 0 or 1
 *  after a simple MOD division.
**/
$("table.altRow tr:visible").each(function( index ) {  
    $(this).css("background-color", ( index % 2 ? "#DEDFDE" : "#EEECEE" ));
});

Demo: http://jsfiddle.net/uMP5x/8/

Comments