I have an element with an animation started one time at the beegining and an animation running infinitly when hover.
When the mouse goes out, the infinite animation stop but the initial rerun, how can I prevent that ?
Here is an example, I don’t want the kf-initial animation to rerun when mouse goes out.
Thanks !
.foo {
margin: auto;
margin-top: 100px;
padding: 1em;
width: fit-content;
border: solid 1px black;
background: red;
color: white;
font-size: 2em;
/* The initial animation */
animation: kf-initial 2s;
}
.foo:hover {
/* The infinite animation */
animation: kf-hover 10s infinite;
}
@keyframes kf-initial {
from {transform: scale(0.2)}
to {transform: scale(1)}
}
@keyframes kf-hover {
100% {transform: rotate(1turn)}
}
<div class="foo">
Hello world
</div>
>Solution :
If you do not want the initial state animation to run again after you mouse out of the hover state and you want the element to return to its previous orientation. You will need to add a class to the foo element using JavaScript and add in CSS for that class that no longer allows that animation to run.
const fooEl = document.querySelector(".foo");
fooEl.addEventListener("mouseleave", () => {
fooEl.classList.add("stopped");
})
.foo {
margin: auto;
margin-top: 100px;
padding: 1em;
width: fit-content;
border: solid 1px black;
background: red;
color: white;
font-size: 2em;
/* The initial animation */
animation: kf-initial 2s;
}
.stopped {
animation: none;
}
.foo:hover {
/* The infinite animation */
animation: kf-hover 10s infinite;
}
@keyframes kf-initial {
from {transform: scale(0.2)}
to {transform: scale(1)}
}
@keyframes kf-hover {
100% {transform: rotate(1turn)}
}
<div class="foo">
Hello world
</div>