One of my current projects requires highlighting a table row when the mouse cursor passes over it. A clean way to do this is to implement a tr:hover class in CSS over the targeted rows. Unfortunately, this CSS pseudo-class (:hover) does not work in Internet Explorer 6 (or earlier), as this browser only allows the use of :hover for the <a> elements.
Safari and Mozilla Firefox handle the :hover pseudo-class without any issues; Internet Explorer 7 requires a standards-compliant mode declared in the HTML file (strict !DOCTYPE).
Coming back to our cross-browser solution: the easiest way is to use Javascript along with CSS. At page load, a Javascript function attaches actions to onMouseOver and onMouseOut events for the tagged rows; the action in itself is very short: change the row’s class to a CSS defined class.
<script>
function highlightTableRows(){
if (!document.getElementById) return
var e = document.getElementsByTagName('tr');
for(var i = 0; i < e.length; i++){
if (e[i].className == 'trHighlight') {
e[i].onmouseover = function(){
this.className = 'trHighlightOn';
}
e[i].onmouseout = function(){
this.className = 'trHighlight';
}
}
}
}
highlightTableRows();
</script>
The table definition must include highlight rows marked with class ‘trHighlight’:
<table>
<tr class="trHighlight">
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
</table>
The CSS definitions must include the two classes as referred in the Javascript code: ‘trHighlight’ and ‘trHighlightOn’:
.trHighlight {
background-color: ;
}
.trHighlightOn {
background-color: #edf3fe;
}






Leave a Reply!