Search code examples
jquerycssinternet-explorerinternet-explorer-6pseudo-class

Get "#myDiv:hover" style from specified in CSS-file with jQuery or similar


I need to check if any ":hover" or ":active" styles are specified for some elements in the CSS rules. I need to loop through these elements if they have the rules specified, on $(document).ready to add some events for ie6 which do not support ":hover" or ":active" on div's.

I could add a class to the specific elements that needs to be "fixed" but I would like the script to be able to work based on what is specified in the CSS. That would make it more dynamic...

$('#elem').is(":hover") won't help to select the element since I need to know before actually hovering.

Maybe this is hard/impossible to do without loading the file "ajax-style" which is not an option...

PS: yes, of course use of IE6 should not be encouraged, but China with 200 million XP machines and 22% IE6 (as of march 2014) is a very important market (source).


Solution

  • You could scan all the css rules for selectors containing :hover or :active, then process the cssText of those rules however you like.

    var iSheet, sheet, iRule, rules, rule;
    for (iSheet=0; iSheet<document.styleSheets.length; iSheet++) {
        sheet = document.styleSheets[iSheet];
        rules = sheet.rules || sheet.cssRules;
        for (iRule=0; iRule<rules.length; iRule++) {
            rule = rules[iRule];        
            if (rule.selectorText.indexOf(":hover") > -1) {
                console.log(rule.cssText);
            }
        }
    }
    

    Here is a jsfiddle.