Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 760
GreenBear Avatar asked Jun 19 '11 21:06

GreenBear


2 Answers

You can't modify them directly but you can insert the CSS to the head portion of the DOM.

like image 168
Emil Avatar answered Oct 03 '22 01:10

Emil


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.

like image 42
Björn Landmesser Avatar answered Oct 03 '22 00:10

Björn Landmesser