I have a button that has a color change when hovering. And in Script the button color changes when a click event occurs. However, Hover works when the page is loaded but after the color changes, it doesn’t work. The code is below:
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "white";
count = 1;
} else {
property.style.backgroundColor = color;
count = 0;
}
}
.button {
background-color: #4caf50;
/* Green */
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
transition-duration: 0.4s;
cursor: pointer;
}
.button1 {
background-color: white;
color: black;
border: 2px solid #4caf50;
}
.button1:hover {
background-color: red;
color: black;
border: 2px solid #4caf50;
}
<h2> Hoverable Buttons</h2>
<button id="buttonGreen" class="button button1" onclick="setColor('buttonGreen', '#122256')">
Green</button>
After I click the button event occurs and the color changes to dark blue and the hover do not work.
>Solution :
button click adds inline styles which have higher priority due to that hover property changes are ignored. You can add !important to get rid of the issue
.button1:hover {
background-color: red !important;
color: black !important;
border: 2px solid #4caf50;
}
<html>
<head>
<style>
.button {
background-color: #4caf50; /* Green */
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
transition-duration: 0.4s;
cursor: pointer;
}
.button1 {
background-color: white;
color: black;
border: 2px solid #4caf50;
}
.button1:hover {
background-color: red !important;
color: black !important;
border: 2px solid #4caf50;
}
</style>
<script>
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "white";
count = 1;
} else {
property.style.backgroundColor = color;
count = 0;
}
}
</script>
</head>
<body>
<h2>Hoverable Buttons</h2>
<button
id="buttonGreen"
class="button button1"
onclick="setColor('buttonGreen', '#122256')"
;
>
Green
</button>
</body>
</html>