Style a table whose cells' background color vary from light, medium, and dark. Any given cell's background color is based on the number of its row and column. Cells in odd rows and odd columns are light; cells in odd rows and even columns OR even rows and odd columns are medium; cells in even rows and even columns are dark.
A. For each Row, assign an index;
B. For each Column, assign an index;
C. For each Cell, {
I. Get the index of this Cell's Row;
II. Get the index of this Cell's Column;
III. If (both indices are odd) {add class '.cell-odd-odd';}
IV. Else If ((parent Row is odd && parent Column is even) ||
(parent Row is even && parent Column is odd)) {
add class '.cell-odd-even';
}
V. Else If (both parents are even) {add class '.cell-even-even';}
VI. Else {do nothing;}
}
Now, how can I do this with CSS and JavaScript/jQuery?
EDIT: This is perhaps a better algorithm:
A. For each Row, assign an index;
B. For each Column, assign an index;
C. For each Cell, {
I. Get the index of this Cell's Row;
II. Get the index of this Cell's Column;
III. If (parent Row is odd) {
If (parent Column is odd) {add class '.cell-odd-odd';}
Else {add class '.cell-odd-even';}
} Else {
If (parent Column is odd) {add class '.cell-odd-even';}
Else {add class '.cell-even-even';}
}
}
You can use the :odd and :even selectors on jQuery to traverse your table's rows and cells like this:
var cssColorArr = ["#FCE9D8", "#F9D5B2", "#F7C08B"];
$("#yourTableId>tbody>tr:odd").each(function(i, elm){
$(elm).style("background-color", cssColorAttr[0]);
$(this).find("td:odd").style("background-color", cssColorAttr[1]);
$(this).find("td:even").style("background-color", cssColorAttr[2]);
});
$("#yourTableId>tbody>tr:even").each(function(i, elm){
$(elm).style("background-color", cssColorAttr[1]);
$(this).find("td:odd").style("background-color", cssColorAttr[1]);
$(this).find("td:even").style("background-color", cssColorAttr[2]);
});
I haven't tested it yet but I think you get the idea.