TheLettuceMaster
TheLettuceMaster

Reputation: 15744

Swap Order of table rows but keep Zebra Striping

I have a small jQuery function where I can swap rows by clicking on an up arrow or a down arrow. The row swap works perfectly. What I can't figure out is why my handling of the striping colors is not working. Here is an example if you click the "up" arrow.

    // =================================
    // UP & DOWN (Ordering) Arrows
    // =================================            
    $(".row-up").click(function() {

        var thisRow     = $(this).closest("tr");
        var thisRowBG   = $(thisRow).css("background");

        var aboveRow    = $(this).closest("tr").prev("tr"); 
        var aboveRowBG  = $(aboveRow).css("background");    

        $(thisRow).after($(aboveRow));

        // switch zebra colors
        $(aboveRow).css("background", thisRowBG);   
        $(thisRow).css("background", aboveRowBG);

    }); 

With this code, the colors are not swapping. As you see, I am trying to save the instances of the two rows involve in the swap and then switch them. This needs to work in IE8.

EDIT:

The CSS for the colored rows is this:

.st_lr_r1 {
    background-color: #DEEAF1;
}

the "white" row (.st_lr_r0) has no color applied.

Upvotes: 0

Views: 200

Answers (2)

James Martin-Davies
James Martin-Davies

Reputation: 651

You can declare even and odd directly in CSS instead of relying on JS to do it.

table > tbody > tr:nth-child(odd) {
    background-color: #eaeaea;
}
table > tbody > tr:nth-child(even) {
    background-color: #fff;
}   

Fiddle.

IE8?

Using jQuery:

$(document).ready(function() {
    $('table > tbody > tr:nth-child(even)').addClass('st_lr_r0');
    $('table > tbody > tr:nth-child(odd)').addClass('st_lr_r1');
});

Fiddle.

Yes, using the same selector through jQuery will work with IE8. :)

Upvotes: 3

lharby
lharby

Reputation: 3265

How about this then (needs testing)

$( "tr:odd" ).css( "background-color", "#DEEAF1" );

I lifted this straight from the jquery odd selector page. Obviously you can modify it to suit your needs.

http://api.jquery.com/odd-selector/

Upvotes: 2

Related Questions