When we represent some data in a grid view we usually prefer to set alternative row color. For this we can use two css classes with different background colors or inline styles. What we need to do is that while constructing the grid by looping through data set, we can check the loop count is odd or even and then attach an alternative class or inline CSS accordingly. |
Suppose we need two alternative colors ‘#ffffff’ and ‘#dedede’ .
Using jQuery we can do this very easily. jQuery provides :even and :odd selectors through which we can select odd and even element and set background color. Take example of the following table |
test data 1 |
test data 2 |
test data 3 |
test data 4 |
test data 5 |
test data 6 |
test data 7 |
test data 8 |
test data 9 |
test data 10 |
$(document).ready(function(){ $("#grid tr:even").css("background-color", "#dedede"); $("#grid tr:odd").css("background-color", "#ffffff"); });
If you want to set different set of alternative colors for both table then just give different ids to the table and use it.
Here I use grid1 and grid2 as ids for two tables.
test data 1 |
test data 2 |
test data 3 |
test data 4 |
test data 5 |
test data 6 |
test data 7 |
test data 8 |
test data 9 |
test data 10 |
$(document).ready(function(){ $("#grid1 tr:even").css("background-color", "#dedede"); $("#grid1 tr:odd").css("background-color", "#ffffff"); $("#gri2 tr:even").css("background-color", "#bbbbff"); $("#grid2 tr:odd").css("background-color", "#ffffff"); });
If you want to use css class for every alternative row then you have to change the javascript. As an example I take two css classes – classOdd and classEven.
$(document).ready(function(){ $("#grid tr:even").addClass('classEven'); $("#grid tr:odd").addClass('classOdd'); });