1

I'm trying to write some automated tests and for some elements the css selector ":hover/:focus" is present , Obviously i can't simulate hover state with pure javascript . So after a bit of searching i've came across this question: How do I simulate a mouseover in pure JavaScript that activates the CSS ":hover"?

And one of the answers gives this snippet :

simulateCssEvent = function(type){
    var id = 'simulatedStyle';

    var generateEvent = function(selector){
        var style = "";
        for (var i in document.styleSheets) {
            var rules = document.styleSheets[i].cssRules;
            for (var r in rules) {
                if(rules[r].cssText && rules[r].selectorText){
                    if(rules[r].selectorText.indexOf(selector) > -1){
                        var regex = new RegExp(selector,"g")
                        var text = rules[r].cssText.replace(regex,"");
                        style += text+"\n";
                    }
                }
            }
        }
        $("head").append("<style id="+id+">"+style+"</style>");
    };

    var stopEvent = function(){
        $("#"+id).remove();
    };

    switch(type) {
        case "hover":
            return generateEvent(":hover");
        case "stop":
            return stopEvent();
    }
}

I've actually tried it and its works reasonably ok until i've encountered selectors like:

testdiv > :hover

testdiv > :hover > #testdiv2

after removing ":hover" with the above code the selector will be invalid.

any bulletproof approach for this?

Community
  • 1
  • 1
avi dahan
  • 539
  • 3
  • 19
  • 3
    I would append `*` to any `:hover` alone so if it get removed you will keep `*` and the selector will be valid – Temani Afif Jan 29 '19 at 14:12
  • @TemaniAfif if you mean to replace ":hover" with "*" that will not work because selectors like "#test1:hover" will become "#test1*" which will not work – avi dahan Jan 29 '19 at 14:24
  • I meant if you find a :hover with a *space* before (only if there is a space before) you put `*` before it then you won't have any issue – Temani Afif Jan 29 '19 at 14:26
  • @TemaniAfif but i don't think that space is mandatory , the selector " testdiv>:hover>#testdiv2" is also valid , I'm trying to avoid using regex – avi dahan Jan 29 '19 at 14:30
  • well, the logic still apply .. a space or a selector such `> ~ +`, you can easily enumerate them I guess – Temani Afif Jan 29 '19 at 14:33

0 Answers0