leora
leora

Reputation: 196489

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?

Upvotes: 4

Views: 2573

Answers (3)

Gokul Rama
Gokul Rama

Reputation: 1

I searched all over stackoverflow for an answer and I didn't get any. Then finally my manager helped me out with this. So for whichever row (<tr> element) that you want to style, create a ui:field entry in the ui.xml binder file.

<tr ui:field="stylingRow">

then in the corresponding Java class use the @UiField annotation to get this particular row's DOM element.

@UiField TableRowElement stylingRow;

Then you can do anything with that.. Add styles and the like...

stylingRow.getStyle().setBackgroundColor("black");

There are a plethora of methods available in the TableRowElement, So if only a couple of rows are hidden or something and you need the zebra styling for all the visible ones.. you can manually change the style of the hidden ones using the above statements.

Upvotes: 0

MackieeE
MackieeE

Reputation: 11862

/**
 *  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/

Upvotes: 5

Lachezar
Lachezar

Reputation: 6703

CSS3 gives you neat way of doing this:

 tr:nth-child(odd) { 
      background-color:  #000;  
 }
 tr:nth-child(even) { 
      background-color:  #FFF;
 }

This will set color only on the visible rows.

Upvotes: -2

Related Questions