Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting every second visible table row

I have a table displaying a tree structure (Super- and Subcategories). When the user clicks on a supercategory, the display property of the childs is toggeled.

Now I want to add an alternating background color on every second table row - but of course taking only those into account which are currently visible. Below is a simplified example of the structure:

<table>
    <tr data-level="0"><td>Super 1</td></tr>
    <tr class="hide" data-level="1"><td>Sub 1</td></tr>
    <tr data-level="0"><td>Super 2</td></tr>
    <tr class="hide" data-level="1"><td>Sub 2</td></tr>
    <tr class="hide" data-level="1"><td>Sub 3</td></tr>
    <tr class="hide" data-level="1"><td>Sub 4</td></tr>
</table>

When the user clicks on the "Super 2" element, the "hide" classes are removed from the child elements.

I tried several selectors, e.g.:

/* Ugly result (dosn't recognize that elements are hidden) */
tr:nth-child(2n)
{
    background-color: grey;
}

/* Doesn't work at all */
tr:visible:nth-child(2n)
{
    background-color: grey;
}

/* Not what I inteded to do */
tr:not(.hide):nth-child(2n)
{
    background-color: grey;
}

I hope I got clear on what i want to do.

Is that possible with CSS or should I write a JS script that recalulates the even and odd rows whenever anything changes? Thanks in advance for any hints!

like image 874
Oromis Avatar asked Mar 11 '12 16:03

Oromis


2 Answers

You said the hide class is removed onclick.
Keep it simple, and add a class IE: "show".

.show tr:nth-child(odd)    { background-color:#eee; }
.show tr:nth-child(even)   { background-color:#fff; }

Edit:
I'll blame exaustion, but I think this might be the correct syntax.

tr.show:nth-child(odd)    { background-color:#eee; }
tr.show:nth-child(even)   { background-color:#fff; }
like image 118
Bradmage Avatar answered Oct 04 '22 16:10

Bradmage


This jQuery snippet will do the job:

$('tr').removeClass('alternate')​
$('tr:not(.hide):odd').addClass('alternate')​

Play with it on the jsFiddle

like image 31
Manuel Ebert Avatar answered Oct 04 '22 15:10

Manuel Ebert