Reputation: 27
JS Fiddle: https://jsfiddle.net/q3ahefdg/2/
If you hover before clicking on "Capitol 1" you will see the background color changing, but after you show and then hide the elements, if you hover again over "Capitol 1" you won't see the color changing.
How can I make the color change after clicking (like before) ?
function functie() {
var x = document.getElementById("Elemente");
if (x.style.display === "none") {
document.getElementById("Buton1").style.backgroundColor = "rgb(132, 197, 232)";
x.style.display = "block";
} else {
document.getElementById("Buton1").style.backgroundColor = "rgb(154, 208, 237)";
x.style.display = "none";
}
}
Upvotes: 2
Views: 63
Reputation: 246
The problem is that inline styles, which is what you are setting through JS, take precedence over the ones that come from CSS classes, due to CSS specificity rules.
Adding a !important
declaration on the hover background, like this, works:
.LinkBaraStanga:hover {
background-color: rgb(132, 197, 232) !important;
}
However, a better solution would be creating different classes for the different cases of the button, so you can better manage the different states, and don't run into the problem of having to override a previous !important
declaration:
.LinkBaraStanga--off {
background-color: rgb(154, 208, 237);
...
}
.LinkBaraStanga--off:hover {
background-color: rgb(132, 197, 232);
}
.LinkBaraStanga--on {
background-color: rgb(154, 208, 237);
}
And then instead of setting the element's style
via JS, add or remove the desired classes. For example:
<button class="LinkBaraStanga LinkBaraStanga--off">
And on the JS, call these functions together to toggle between both classes:
element.classList.toggle('LinkBaraStanga--on')
element.classList.toggle('LinkBaraStanga--off')
For more information on how to set the classes of an element, refer to classList on MDN.
Upvotes: 1
Reputation: 91
A much better way would be to get the background-color: rgb(132, 197, 232);
in a seperate class, and then just toggle that whenever you like.
You can apply it like this:
var element = document.getElementById("myDIV");
element.classList.toggle("clicked");
where the css is:
.clicked {background-color: rgb(132, 197, 232);}
and it should work properly
Upvotes: 3
Reputation: 27
Fixed it. Just had to add "!important" in the hover class:
.LinkBaraStanga:hover { background-color: rgb(132, 197, 232)!important; }
Upvotes: 0