Firefox is smart. It has the :hover pseudo-class already functioning. IE, on the other hand, can only apply :hover to anchors.
To get the behavior in IE, we need a simple little script that allows us to append and unappend a class on hover. It's just that simple.
Here's the javascript code:
// apply this only for IE
if (document.all && document.getElementById) {
function _IEonHover(element) {
element.className += ' hover';
}
function _IEonUnHover(element) {
element.className = element.className.replace(' hover', '');
}
function _IEAddArbitraryHover() {
/* An array of elements to apply this "trick" to.
This example, adds hover to tr and td elements.
You can use the * to get EVERY element
alternatively, you could type any element
name to be specific
var aHover = ['*']; for example... however, this
will be very slow.
*/
var aHover = ['td', 'tr'];
for (var j = 0, jLen = aHover.length; j < jLen; j++) {
var els = document.getElementsByTagName(aHover[j]);
// loop over every element and add the hovering/unhovering
for (var i = 0, eLen = els.length; i < eLen; i++) {
/* adds the hovering function, we can't attachEvent
because there's no way to get the target of the event, only the source element */
els[i].onmouseover = function () { _IEonHover(this); };
els[i].onmouseout = function () { _IEonUnHover(this); };
}
}
}
attachEvent('onload', _IEAddArbitraryHover);
}
This function works by adding and removing the class "hover." So, in our CSS, whereever we have a :hover we also need to add a .hover. So, for example:
p:hover, p.hover { background-color: #efefef; }
The other nice thing about this, is IE is able to do complex things on hover as well. For example:
| Column 1 | Column 2 | Column 3 |
|---|---|---|
| Lorem ipsum dolor sit amet, consectetuer adipiscing elit | Vivamus cursus iaculis ante. | Etiam mi nulla, porttitor vitae, euismod in, pharetra in |
| Lorem ipsum dolor sit amet, consectetuer adipiscing elit | Vivamus cursus iaculis ante. | Etiam mi nulla, porttitor vitae, euismod in, pharetra in |
| Lorem ipsum dolor sit amet, consectetuer adipiscing elit | Vivamus cursus iaculis ante. | Etiam mi nulla, porttitor vitae, euismod in, pharetra in |
This effect is acheived by this CSS:
table { border: 1px solid #000; width: 75%; table-layout: fixed; }
tr td { border: 1px solid #000; padding: .5em; }
tbody tr:hover, tbody tr.hover { background-color: #eee; }
tbody tr:hover td, tbody tr.hover td { border-color: #900; }
tbody tr:hover td:hover, tbody tr.hover td.hover { background-color: #ffcc00; }
tbody td:hover, tbody td.hover { color: #006600; }