This example takes a different tack to achieve the goal. The change is applied to each cell in a row instead of to the parent row element. This is useful in achieving special effects where each cell is not the same but styled depending on some property of the cell.
In this example the middle cell's highlight colors are the reverse of the outer to cells, or if the cell is a header (TH) the hightlight is different. Here's the CSS that specifies the highlight colors.
.hlt0 { /* Outer columns*/ background-color: yellow; color: black; } .hlt1 { /* Middle column */ background-color: black; color: yellow; } .hlt-th { /* Headers */ background-color: red; }
Try it! Run your mouse over the table and see the cell colors change.
Column1 | Column2 | Column3 |
---|---|---|
Data 1.1 | Data 1.2 | Data 1.3 |
Data 2.1 | Data 2.2 | Data 2.3 |
Data 3.1 | Data 3.2 | Data 3.3 |
Data 4.1 | Data 4.2 | Data 4.3 |
Now let's take a look at the JavaScript. As you can see the function mouse_event isn't very different than it was on the previous page.
function mouse_event (e) { var e = e || window.event; var obj = e.srcElement || e.target; var tname = (obj.nodeType == 1) ? obj.tagName.toLowerCase() : ''; while(tname != "tr" && tname !="table"){ obj= obj.parentNode || obj.parentElement; tname = obj.tagName.toLowerCase(); } if (tn == "tr") { var newClass1, newClass0; switch (e.type) { case 'mouseout': newClass1 = newClass0 = ''; break; case 'mouseover': if (obj.cells[0].tagName.toLowerCase() == "th") newClass1 = newClass0 = "hlt-th"; else { newClass1 = 'hlt1'; newClass0 = 'hlt0'; } break; } for (var i = 0, x = 0; i < obj.cells.length; i++, x = i%2) { if (x) obj.cells[i].className = newClass1; else obj.cells[i].className = newClass0; } } }//eof mouse_event
The switch statement has been changed to assign the needed class names to variables. There are two because there is a maximum of two different classes applied to the cells: one for the outer cells and one the middle cell.
The big change here is the for loop. One property of the row (TR) object is the cells collection, which is an array of pointers to each cell (TD or TH) in the row. The loop walks along each cell in the row assigning a new value to the cell's (TD or TH) class.
Just to add some variation a variable x was added to the for loop. It hold the modulus of i divided by 2, and provides an odd/even indicator. Even cells (0 and 2) get newClass0 and the odd cell (1) get newClass1. The switch statement determined what class was in the variables based on the event type and the tag name of the first cell in the row.