I'm displaying a simple box over an image, I want it to highlight when hovered over and change colour when clicked.
I've got it to highlight when hovered over and change colour when clicked.The problem is that after changing colour the first time it no longer highlights when hovered over. It seems when the JS changes the styles it disables the CSS hover selector.
How can I keep the hover highlighting working?
const box = document.getElementsByClassName("box")[0];
box.addEventListener("click", (e) => {
// console.log(e);
if (e.target.style.backgroundColor == "rgba(255, 0, 0, 0.1)") {
e.target.style.backgroundColor = "rgba(0, 255, 0, 0.1)";
e.target.style.borderColor = "rgba(0, 255, 0, 0.4)";
} else {
e.target.style.backgroundColor = "rgba(255, 0, 0, 0.1)";
e.target.style.borderColor = "rgba(255, 0, 0, 0.4)";
}
});
.container {
position: relative;
}
.box {
width: 40px;
height: 40px;
background-color: rgba(0, 255, 0, 0.1);
border-style: solid;
border-color: rgb(0, 255, 0);
position: absolute;
top: 20px;
left: 50px;
}
.box:hover {
background-color: rgba(32, 58, 58, 0.4);
}
<div class="container" style="display: inline-block">
<img src="https://pixeljoint.com/files/icons/full/tree__r1090291261.gif"></img>
<div class="box"></div>
</div>
ifelsestatement does not make any sense! You are doing the same thing in both conditions.