Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to do alternating background color on visible HTML table rows

I have a HTML table where I am dynamically adding and hiding rows and I want the current set of visible rows to always show with alternative backcolor for easy reading.

I have the following code that works fine functionally, but is really slow (especially on Internet Explorer browsers)

$('table.alternateRow tr:visible').removeClass('odd').filter(':odd').addClass('odd');

here is my css:

.alternateRow tr {
    background-color: #FFFFFF;
}

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

Is there any faster solution for this code above that applies to visible rows but doesn't freeze in Internet Explorer. My table has about 150 - 200 rows visible

Also, (for certain reasons) I want to avoid paging if possible (as a last resort) as it makes the report much harder to read

like image 376
leora Avatar asked Jun 23 '11 11:06

leora


2 Answers

The code in your question iterates over the table rows twice (once to remove the odd class, once to filter the rows), then performs a final pass over the filtered rows to add the odd class.

It might be faster to iterate over the rows only once, using each():

$("table.alternateRow tr:visible").each(function(index) {
    var $this = $(this);
    if (index & 1) {
        $this.addClass("odd");
    } else {
        $this.removeClass("odd");
    }
});
like image 99
Frédéric Hamidi Avatar answered Sep 17 '22 15:09

Frédéric Hamidi


With CSS 3 (IE9) you can do the following

tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}

Although this will not take into account visibility - it does give you a useful selector (odd/even)

above: Uses CSS doesn't take into account visibility

Edit - added clarification incase someone doesn't read all the way to the end

below: Uses Jquery DOES take into account visibility

With jQuery (which effectively allows IE 8 and lower to support CSS3) you can put the odd/even part straight into your selector...

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

edit combined into function

function zebra(){
    $('table.alternateRow tr').removeClass('even', 'odd');
    $('table.alternateRow tr:visible:even').addClass('even');
    $('table.alternateRow tr:visible:odd').addClass('odd');
}

This is maybe off topic but have you seen the jquery datatables plugin?

http://www.datatables.net/

It handles this sort of stuff seemlessly

like image 20
calumbrodie Avatar answered Sep 19 '22 15:09

calumbrodie