I have a button where it’s background changes when you hover, as well as when you click it. To make it so it changes when you click, I made it to where you use the mousedown
event. This seems to override the mouseenter
and mouseleave
events. When the mousedown
event happens, it seems to disable the CSS hover events. I have already tried to add mouseenter and mouseleave, and it hasn’t worked.
let button = document.querySelector(".shoot");
button.addEventListener("mousedown",()=>{
// REMEMBER TO FIX HOVER EFFECTS
button.style.backgroundColor = "dodgerblue";
})
button.addEventListener("mouseup",()=>{
button.style.backgroundColor = "#d3d3d3";
})
.shoot {
width:200px;
padding-top:20px;
height:40px;
font-size:18px;
background-color:#d3d3d3;
border-radius:30px;
font-family:Semi-Casual;
color:white;
text-align:center;
margin:auto;
}
.shoot:hover {
background-color:#c3c3c3;
cursor:pointer;
}
<div class="shoot">
Shoot
</div>
2
Answers
Use event
mouseover
/mouseout
. Also don’t forcemouseup
on the element as it won’t do what you want because if i drag the mouse out the thing is still thereInline styles will take precedence over the CSS rules defined in a stylesheet, so that’s why the hover effect is not working as expected.
So, instead of using Javascript to set the backgroundColor directly, use javascript to add a css class to the element, which ultimately uses CSS (also) to set the background-color.