4

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?

Michael M.
11.2k11 gold badges22 silver badges46 bronze badges
asked Aug 16, 2009 at 18:50
1
  • you might want to revisit this question. The owner of the accepted answer has edited it to point out that it is wrong. Commented Oct 31, 2022 at 11:14

5 Answers 5

11

Using getComputedStyle as on the accepted answer won't work, because:

  1. The computed style for the hover state is only available when the element is actually on that state.
  2. The second parameter to getComputedStyle should be empty or a pseudo-element. It doesn't work with :hover because it's a pseudo-class.

Here is an alternative solution:

function getCssPropertyForRule(rule, prop) {
 var sheets = document.styleSheets;
 var slen = sheets.length;
 for(var i=0; i<slen; i++) {
 var rules = document.styleSheets[i].cssRules;
 var rlen = rules.length;
 for(var j=0; j<rlen; j++) {
 if(rules[j].selectorText == rule) {
 return rules[j].style[prop];
 }
 }
 }
}
// Get the "color" value defined on a "div:hover" rule,
// and output it to the console
console.log(getCssPropertyForRule('div:hover', 'color'));

Demo

answered Sep 27, 2012 at 19:52

2 Comments

Suspiciously identical, but this answer's method allows for selectors that aren't the entire rule selector.
This will not work on stylesheets on other domains due to domain restrictions. so it's partial solution
4

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.

answered Aug 16, 2009 at 19:33

2 Comments

stylesheets loaded from external files are not available in document.styleSheets.
@JacobRask — That's not true. External files are accessible. Cross-origin files are not by default but can be accessed via <link rel="stylesheet" href="//example.com/css" crossorigin="anonymous" /> + a suitable access-control-allow-origin header on the response from example.com.
1

UPDATE: I somehow got this wrong. The below example doesn't work. See @bfavaretto's comment for an explanation.

(削除) 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.

answered Aug 16, 2009 at 19:54

10 Comments

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.
@david, out of curiosity, how are you going to handle the IE issue?
@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, 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.
This won't work, because getComputedStyle expects a pseudo-element as the second parameter, and hover is a pseudo class. If you remove that, it will work, but will only give you the hover value if it runs while the element is actually on hover state. demo.
|
0

If there are any people here who use the questions accepted answer but it won't work, here's a nice function that might:

function getPseudoStyle(id, style) {
 var all = document.getElementsByTagName("*");
 for (var i=0, max=all.length; i < max; i++) {
 var targetrule = "";
 if (all[i].id === id) {
 if(all[i].selectorText.toLowerCase()== id + ":" + style) { //example. find "a:hover" rule
 targetrule=myrules[i]
 }
 }
 return targetrule;
 }
}
Zach Saucier
26.2k12 gold badges101 silver badges161 bronze badges
answered Sep 27, 2012 at 19:20

1 Comment

This is a very specific approach that will only work if (a) the CSS selector that applies the rule uses a single ID selector + single psuedo-class (b) it isn't overridden by the cascade and (c) you define myrules (which, as it stands, will cause the code to throw a reference error) and (d) the element you are looking for is the last element in the document which meets condition A.
-1

There is an alterantive way to get :hover pseudo class with javascript. You can write your styles of hover pseudo class in a content property.

p::before,
p::after{
 content: 'background-color: blue; color:blue; font-size: 14px;';
}

then read from it via getComputedStyle() method:

console.log(getComputedStyle(document.querySelector('p'),':before').getPropertyValue('content'));
answered Jun 29, 2020 at 17:45

1 Comment

The is an incredibly fragile approach that depends on the developer keeping the content value and :hover rules in sync while accounting for the cascade.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.