Home > Net >  Is there any way to check if an element has any changes on mouseover by javascript?
Is there any way to check if an element has any changes on mouseover by javascript?

Time:12-22

I want to detect if an element has any changes, such as the background-color changes to another or cursor changes to pointer, on mouseover by javascript.

I thought about using getComputedStyle(element, ":hover") but this is not available with :hover pseudo.

I also tried to simulate mouse over by jQuery like below, but it seems like it does not work as I expected.

$obj.css('cursor')
$obj.mouseover().css('cursor')

Is there any good way?

CodePudding user response:

You could add an eventlistener, such as "mouseenter" and then console log every time the mouse hovers over an element.

If you test out this code, you will see that the number of times you have hovered over the list items will appear in the console.

here is a link to "mouseover" event documentation, which I used and edited to help simplify my answer.

https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    
<ul id="test">
    <li>Check if item has been hovered over</li>
    <li>item 2</li>
  </ul>


  <script>
    let test = document.getElementById("test");
      // This handler will be executed only once when the cursor moves over the unordered list
      test.addEventListener("mouseenter", function( event ) {
        // highlight the mouseenter target
        console.log("purple has been hovered over")
        event.target.style.color = "purple";
        // reset the color after a short delay
        setTimeout(function() {
          event.target.style.color = "";
        }, 500);
      }, false);
 
</script>


</body>
</html>

CodePudding user response:

Unfortunately, you can't do it via jQuery like that. You probably need to get the stylesheets for the document and manually iterate through them to find matches to your selector.

function getCss(cssSelector){
    var styleSheets = document.styleSheets;
    var matchedRules = [];
    for(var i = 0; i < styleSheets.length; i  ) {
        var rules = styleSheets[i].rules || sheets[i].cssRules;
        for (var j = 0; j < rules.length; j  ) {
            if (rules[j].selectorText === cssSelector) {
                matchedRules.push(rules[j].cssText);
            }
        }
    }
    return matchedRules;
}

You can then call the function to obtain the matched rules. For example:

getCss(".a:hover");
  • Related