colour alternative rows

JQuery colour alternate table rows

Posted on: June 7th, 2013 by taff No Comments

 

Colouring alternate table rows increases readability, thus increasing usability. In particular long table rows with the same background colour being hard to read is a phenomenon that most of us know well from using MS Excel. The same goes for long tables in our browser where, in a worst case, we need to scroll the entire view.

Using jQuery to colour alternate table rows may sound strange when CSS now offers exactly that with the use of a pseudo selector.

Colour alternate table rows with CSS pseudo selector

tr:nth-child(even) {
background-color: #f8f8f8;
}

Unfortunately, and probably not that surprising for most of you, Internet Explorer 8 doesn't like the css solution. I am currently building an MIS for a large company and their browser of choice at the moment is, yes you guessed it, IE8 so I had to resort to a javascript solution. JQuery was already in use so I simply did the following

Colour alternate table rows with jQuery

$("tr:even").css("background-color", "#f8f8f8");

If I for whatver reason have no default background colour for my table rows I can use a short hand version of the if / else conditional like this

$("#idOgTable tbody tr").css("background-color", function(index) {
return index%2==0?"#f8f8f8":"#ffffff";
});

Due to my table setup using thead, tbody and tfoot tags I have the tbody in the selector. I needed this setup to allow me to use the amazing tablesorter plugin to exclude rows when sorting.

I hope you can use the above script to colour alternate table rows with jQuery.