1

I have an element which changes opacity when hovered. At some point during my javascript, I change the base opacity value of this element. However, even if I change the property back to its original value, the :hover selector no longer triggers.
This is how the code works without changing the base value:

#hover-div:hover{
      opacity:1;
    }
#hover-div{
  background:red;
  opacity:0.7;
}
  <div id = 'hover-div'>
    Hover on me.
  </div>

As expected, the div becomes fully opaque when hovered. However, if I now introduce two lines of javascript which set and then reset the opacity value, the hover effect no longer triggers:

document.getElementById('hover-div').style.opacity = '1';
document.getElementById('hover-div').style.opacity = '0.7';
#hover-div:hover{
      opacity:1;
    }
#hover-div{
  background:red;
  opacity:0.7;
}
<div id = 'hover-div'>
    Hover on me.
  </div>

How can I change the base value using js while still keeping the effects of the css hover? (preferably using vanilla js/css)

Leaf the Legend
  • 471
  • 3
  • 9

2 Answers2

2

Because of CSS Specificity, inline styles will always override CSS selectors. What you are looking for is to actually remove the opacity style using removeProperty('opacity') so that the .hover-div selector applies:

document.getElementById('hover-div').style.opacity = '1';
document.getElementById('hover-div').style.removeProperty('opacity');
#hover-div:hover{
  opacity:1;
}

#hover-div{
  background:red;
  opacity:0.7;
}
<div id='hover-div'>
    Hover on me.
</div>
Yuan-Hao Chiang
  • 2,484
  • 9
  • 20
1

That is because the Javascript sets the styles inline, inline styles take precedence over external stylesheet

prabhu
  • 878
  • 9
  • 17