Change :hover CSS properties with JavaScript

271,441

Solution 1

Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.

var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');

if (style.styleSheet) {
    style.styleSheet.cssText = css;
} else {
    style.appendChild(document.createTextNode(css));
}

document.getElementsByTagName('head')[0].appendChild(style);

Solution 2

You can't change or alter the actual :hover selector through Javascript. You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, @Bryan).

Solution 3

What you can do is change the class of your object and define two classes with different hover properties. For example:

.stategood_enabled:hover  { background-color:green}
.stategood_enabled        { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled       { background-color:black}

And this I found on: Change an element's class with JavaScript

function changeClass(object,oldClass,newClass)
{
    // remove:
    //object.className = object.className.replace( /(?:^|\s)oldClass(?!\S)/g , '' );
    // replace:
    var regExp = new RegExp('(?:^|\\s)' + oldClass + '(?!\\S)', 'g');
    object.className = object.className.replace( regExp , newClass );
    // add
    //object.className += " "+newClass;
}

changeClass(myInput.submit,"stategood_disabled"," stategood_enabled");

Solution 4

Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):

HTML:

<button id=Button>Button Title</button>

CSS:

.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}

JavaScript:

var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');

Solution 5

Pretty old question so I figured I'll add a more modern answer. Now that CSS variables are widely supported they can be used to achieve this without the need for JS events or !important.

Taking the OP's example:

<table>
  <tr>
    <td>Hover 1</td>
    <td>Hover 2</td>
  </tr>
</table>

We can now do this in the CSS:

table td:hover {
  // fallback in case we need to support older/non-supported browsers (IE, Opera mini)
  background: #ff0000;
  background: var(--td-background-color);
}

And add the hover state using javascript like so:

const tds = document.querySelectorAll('td');
tds.forEach((td) => {
  td.style.setProperty('--td-background-color', '#00ff00');
});

Here's a working example https://codepen.io/ybentz/pen/RwPoeqb

Share:
271,441
zdebruine
Author by

zdebruine

I write fast Non-negative Matrix Factorization algorithms and apply them to big biology data.

Updated on July 08, 2022

Comments

  • zdebruine
    zdebruine almost 2 years

    How can JavaScript change CSS :hover properties?

    For example:

    HTML

    <table>
      <tr>
        <td>Hover 1</td>
        <td>Hover 2</td>
      </tr>
    </table>
    

    CSS

    table td:hover {
    background:#ff0000;
    }
    

    How can the td :hover properties be modified to, say, background:#00ff00, with JavaScript? I know I could access the style background property using JavaScript with:

    document.getElementsByTagName("td").style.background="#00ff00";
    

    But I don't know of a .style JavaScript equivalent for :hover.

  • zdebruine
    zdebruine almost 12 years
    There really is NO way to change the :hover selector with JavaScript?
  • Admin
    Admin almost 12 years
    Note that you are also going to need to bind mouseleave in order to reverse the effects.
  • Achal Dave
    Achal Dave almost 12 years
    If you're taking this route, this article may help in the future as well.
  • Benji XVI
    Benji XVI almost 8 years
    :hover is a pseudo-class, not a pseudo-element. Pseudo-elements begin with a double colon, e.g. ::after. /nitpick
  • Andi
    Andi over 7 years
    If looking to append the stylesheet, would it not be style.styleSheet.cssText += css;?
  • Adaline Simonian
    Adaline Simonian over 7 years
    @Andi No, because style variable in kennebec's answer is a new element created in the code and doesn't point to an existing <style> tag in the HTML.
  • Yahya
    Yahya almost 7 years
    This will persist the new style and won't go back to its previous one!
  • Gabriel Barberini
    Gabriel Barberini over 6 years
    I just applied this model on my SoloLearn playrground website, check by yourself and see how it works: code.sololearn.com/WEtMpJ0mwFAD/#js
  • GreenAsJade
    GreenAsJade about 6 years
    Why is it unknown whether the new style element already has a styleSheet or not?
  • GreenAsJade
    GreenAsJade about 6 years
    How would you find and edit a current stylesheet rule, to change it? This shows adding a new rule, but what if there already is a rule, and it's just a value being changed?
  • Andrei Volgin
    Andrei Volgin over 5 years
    @Yahya - You can revert this color back on mouse out event.
  • Jester
    Jester over 5 years
    I've been using this on past projects and even tried the accepted answer recently, but this one always prevails when it comes to using hover/active elements with colored buttons. Just want to say thanks for posting this as an option.
  • JGallardo
    JGallardo over 4 years
    voting down because of poor naming convention used for a variable, things like this set newbies up for bad habits.
  • James
    James over 4 years
    @JGallardo what would be better variable names in your opinion?
  • Verano137
    Verano137 over 3 years
    Sorry, did not think it over first. You should also add an other event, when mouse leaves, and if you want to revert back the orig stly, one way, to save it in a variable
  • Gibolt
    Gibolt over 3 years
    Mouse events are not reliable, as people can switch tabs/applications without moving the mouse
  • Atul Mishra
    Atul Mishra about 3 years
    This is only for one button right ? What if i want to add this effect to all the buttons
  • David Spector
    David Spector about 3 years
    JavaScript provides several ways to handle multiple operations, including using arrays.
  • okram
    okram over 2 years
    This answer would be more useful if 1) properly formatted and 2) give more context on what libraries are needed to use this solution. makeStyles is not a global method in browsers just out of the box.
  • leonp5
    leonp5 over 2 years
    Thanks @ybentz, that's a good "workaround".
  • PetCheetah
    PetCheetah about 2 years
    You better use this.style.display="block"; | this.style.display="none";