Search code examples
javascripthtmlcsspseudo-class

How to change a Pseudo-class style through JavaScript?


This example is, for a matter of simplicity, just an illustration of what I need to do. Say, I have an element, which style is set in a CSS. The style is set for the element as well as for a Pseudo-class, say element:hover. I can override the style for the element with the following JavaScript: element.style.setProperty('property-name', 'new value', ''). How can I change the Pseudo-class's style through JavaScript?

Thank you.

<html>
<head>
      <style type='text/css'>
             #myBtn {
                background-color: red;
             }
             #myBtn:hover {
                background-color: blue;
             }
      </style>
</head>
<body>
      <button id='myBtn'>Colored button</button>

      <button onclick="ChangeColor();">Script button</button>

      <script type="application/x-javascript">
              function ChangeColor() {
                 var Btn = document.getElementById('myBtn');
                 Btn.style.setProperty('background-color', 'green', '');
              };
      </script>
</body>
</html>

Solution

  • I would use a different set of rules with an additional class

    <html>
    <head>
      <style type='text/css'>
        #myBtn {
          background-color: red;
        }
        #myBtn:hover {
          background-color: blue;
        }
        #myBtn.changed {
          background-color: green;
        }
        #myBtn.changed:hover {
          background-color: yellow; /* or whatever you want here */
        }
    </head>
    

    And then

    <script type="application/x-javascript">
          function ChangeColor() {
             var btn = document.getElementById('myBtn');
             btn.className = "changed";
          };
    </script>
    

    Of course, this makes only sense for one or a couple of different values you want to have for your color.