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
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");
}
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With