1

I'm new here and I have a question that might be simple but I just couldn't find an answer after googling for a while.

I have some buttons in my browser game that are green with a white text. When I hover over them, I change the rgba with CSS and the green becomes more transparent:

#oneOfTheButtons:hover {
  background: rgba(76, 175, 80, 0.7) !important;
}

The white text stays the same. I also have some Javascript that changes the color if the player goes level up:

document.getElementById("oneOfTheButtons").style.background = "rgba(77, 173, 173, 1)";

Then the buttons are blue. But the problem is that a hover still makes them transparent green, but I want them to be a transparent blue. I have 20 more levels like that with different colors.

Is there any simple solution for this?

  • 1
    Possible duplicate of [Change :hover CSS properties with JavaScript](https://stackoverflow.com/questions/11371550/change-hover-css-properties-with-javascript) – Kevin Lewis Sep 05 '18 at 20:04
  • 1
    Have you tried changing that class of the buttons and having the different classes styled already? – Kevin Lewis Sep 05 '18 at 20:05

2 Answers2

3

This could be done in many different ways, but you could do it with css variables like this:

let green = true;
function toggleColor() {
  if (green) {
    document.body.style.setProperty('--button-bg-color', '77, 173, 173');
  } else {
    document.body.style.setProperty('--button-bg-color', '76, 175, 80');
  }
  green = !green;
}
:root {
  --button-bg-color: 76, 175, 80;
}

button {
  background: rgba(var(--button-bg-color), 1);
}

button:hover {
  background: rgba(var(--button-bg-color), 0.7);
}
<button onclick="toggleColor()">Toggle hover color!</button>
Olian04
  • 6,480
  • 2
  • 27
  • 54
0

You could use the following css

.green:hover {
  background: rgba(76, 175, 80, 0.7);
}
.green {
  background: rgba(76, 175, 80, 1);
}
.blue {
  background: rgba(77, 173, 173, 1);
}
.blue:hover {
  background: rgba(77, 173, 173, 0.7);
}

And the following js

document.getElementById("oneOfTheButtons").className = "blue";
Kevin Lewis
  • 231
  • 1
  • 8