2

I want to sniff the color which a link would become if I hovered over it without actually hovering over it. The reason I want to do this is so I know what to change it back to using animate as the colour can be set via various skins which would be applied dynamically. Can I do this using javascript or jquery ( or is there any other way to do it ) ?

Edit: I already have implemented this using CSS transitions but I need the javascript for IE9 and below

byronyasgur
  • 4,627
  • 13
  • 52
  • 96

3 Answers3

6

No, this isn't possible unfortunately: you can use getComputedStyle() to retrieve information about pseudo-elements (::before/::after), but not the :hover pseudo-selector.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
4

You can get the value from the stylesheets: http://jsfiddle.net/wt3qQ/

// code I found here: http://catcode.com/dominfo/getstyle2.html
function getStyleBySelector( selector )
   {
       var sheetList = document.styleSheets;
       var ruleList;
       var i, j;

       /* look through stylesheets in reverse order that
          they appear in the document */
       for (i=sheetList.length-1; i >= 0; i--)
       {
           ruleList = sheetList[i].cssRules;
           for (j=0; j<ruleList.length; j++)
           {
               if (ruleList[j].type == CSSRule.STYLE_RULE && 
                   ruleList[j].selectorText == selector)
               {
                   return ruleList[j].style;
               }   
           }
       }
       return null;
   }

console.log(getStyleBySelector('a:hover').color);
console.log(getStyleBySelector('#link:hover').color);
Shmiddty
  • 13,847
  • 1
  • 35
  • 52
  • nice, although one would need to know the exact selector used in the css, you cannot work it out from the element.. – Gabriele Petrioli Nov 30 '12 at 19:48
  • Thanks. Yes, the fiddle seems to work; however I'm not going to implement or test it out myself because it looks a bit more than I want to venture into at the moment so think I will just ignore – byronyasgur Nov 30 '12 at 20:51
  • This unfortunately won't work if the CSS stylesheet is cross-domain as you won't be able to access document.styleSheets for it – Rhys Dec 08 '16 at 17:22
3

If you mean to animate the color, then (for modern browsers) you could enable transitions for the color and that way it will animate automatically to whatever it becomes on :hover

To apply with code you could do

$('element').css({
   '-webkit-transition':'color 0.5s',
   '-moz-transition':'color 0.5s',
   '-o-transition':'color 0.5s',
   'transition':'color 0.5s',
});
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • Thanks but sorry (and I should have mentioned this in the question) but the reason I wanted this was that I was doing a fallback for IE9 and below. – byronyasgur Nov 30 '12 at 20:05