In a website I'm building, I have a button with a :hover animation, and when you click the button a lot of things on the page including the button move around. My problem is that even after the button moves out from under the mouse, it doesn't update and lose its :hover effect until you move the mouse again.
Here's an example - here once you click the button it stays light blue (the hovered colour) until you move the mouse again.
function clicked() {
if (document.getElementById('mydiv').style.transform == 'translateY(70px)') {
document.getElementById('mydiv').style.transform = 'translateY(0px)';
} else {
document.getElementById('mydiv').style.transform = 'translateY(70px)';
}
};
div {
background-color: #fedcba;
padding: 20px;
display: inline-block;
}
div:hover {
background-color: #abcdef;
}
<div id="mydiv" onclick="clicked();">Click me</div>
How do I make the element update without the user needing to move the mouse again? JQuery is ok.
I think with your current CSS approach you won't be able to handle that. Try another JavaScript approach:
const el = document.getElementById('mydiv');
el.addEventListener('click', () => {
if(el.style.transform == 'translateY(50px)') {
el.style.transform = 'translateY(0px)';
} else {
el.style.transform = 'translateY(50px)';
}
el.style.background = "#fedcba";
});
el.addEventListener('mouseover', () => {
el.style.background = "#abcdef";
});
el.addEventListener('mouseout', () => {
el.style.background = "#fedcba";
});
div {
background: #fedcba;
padding: 20px;
display: inline-block;
}
<div id="mydiv">Click me</div>
If you extract the "hover" into the JS code then you can update the state of the element without the user having to move the mouse.