Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hover animation makes initial animation rerun after mouse out

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading