It would be great one day when we could finally highlight table rows with one line of CSS code like this:
table tr:hover td { background:#ccc; }
But unfortunately IE6 only supports :hover pseudo-class on <a> elements. And my testing showed that Opera and Firefox had weird problems with this code on TDs with borders. A way round this is to add a bit of JavaScript instead of pure CSS solution.
Let’s say there are several tables on the page with the same highlight behavior. Table structure doesn’t matter so I chose the very simple one:
<table> <tr> <td>row 1 column 1</td> <td>row 1 column 2</td> <td>row 1 column 3</td> </tr> <tr> <td>row 2 column 1</td> <td>row 2 column 2</td> <td>row 2 column 3</td> </tr> </table>
On page load the script goes through all the TRs and apply “onhover” event handler to each one. To add event handlers I use a great cross-browser function “addEvent” by Peter-Paul Koch. It’s code looks like this:
function addEvent(obj, evType, fn){ if (obj.addEventListener){ obj.addEventListener(evType, fn, false); return true; } else if (obj.attachEvent){ var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } }
And bellow is an example of how to use it:
addEvent(window, 'load', rowHighlightSet);
The function “rowHighlightSet” will be execuled each time you move the mouse over the TR. It goes through all the tables on the page and through each TR of each table and assign “rowHighlight” function as onmouseover and onmouseout event handler. The way I am doing this is the following:
var rowHighlightSet = function(){ var tables = document.getElementsByTagName('table'); for(var i=0,trs; i<tables.length;i++){ var trs = tables[i].getElementsByTagName('tr'); for(var j=0; j<trs.length;j++){ trs[j].onmouseover = trs[j].onmouseout = rowHighlight; } } } [/sourcecode] <p>To change the background colour function "rowHighlight" adds "hovered" class to the row. If there are already classes applied to this rows then you should remove (or replace) only the value of the highlighting class name (and don't forget about spaces between class names).</p> var rowHighlight = function(){ if(this.className!='hovered') this.className='hovered'; else this.className=''; }
And the last bit to add is definition of hovered class in the CSS. I am using a nice colour for my TRs 🙂
.hovered td {background:#d2ebfb;}
Nice and easy!