views:

269

answers:

3

I made a function that overwrite the the :hover of some elements on a page. It fades between the normal and the :hover effect. That for i had to create a .hover class in my CSS file. I think this is a little unclean. How could i read the the :hover pseudo class contents?

+2  A: 

You could access document.styleSheets and look for a rule that is applied on that specific element. But that’s not any cleaner than using a simple additional class.

Gumbo
+2  A: 

In Firefox, Opera and Chrome or any other browser that correctly implements window.getComputedStyle is very simple. You just have to pass "hover" as the second argument:

<!DOCTYPE html>

<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
div {
  display: block;
  width: 200px;
  height: 200px;
  background: red;
}
div:hover {
  background: green;
}
</style>
</head>
<body>

<div></div>

<script type="text/javascript">
window.onload = function () {
    var div = document.getElementsByTagName("div")[0];
    var style = window.getComputedStyle(div, "hover");
    alert(style.backgroundColor);
};
</script>
</body>
</html>

But I don't believe there's yet a solution for Internet Explorer, except for using document.styleSheets as Gumbo suggested. But there will be differences. So, having a .hover class is the best solution so far. Not unclean at all.

Ionuț G. Stan
thx! Maybe its not unclean but the person that uses my function has to know that he has to do .hover class. It would be nice to avoid this.
meo
@david, out of curiosity, how are you going to handle the IE issue?
Ionuț G. Stan
@Ionut: this is a great example of some browser inconsistency which isn't worth your time fixing. If someone is using an inferior browser, they'll still get a working website, it just won't have the nice little touches.
nickf
@nickf, I totally agree with that, but there are cases when the client desperately wants the same look in the browser she's using (IE6). I'm experiencing such issues. Otherwise progressive enhancement is the way to go.
Ionuț G. Stan
i always do progressive enhancement. But we still have something like 30% IE6 hits on our servers, so i cant just ignore it :/ but i would love to
meo
@Ionut: I don't know yet how i gonna handle this. Maybe there just gonna be this ".hover" class to add to the CSS if the user want to use the function in IE browser. In the other case its juste gonna do nothing and let IE use the standart css :hover function.
meo
This doesn't seem work for me in either Firefox 3.6, Chrome 4 or Opera 9.5. The alert just shows the value of the non-hovered background colour. In Firefox and Chrome it alerts `rgb(255, 0, 0)`. In Opera it alerts `#ff0000`.
Phil Ross