damjuve
damjuve

Reputation: 354

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.

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>

Upvotes: 1

Views: 541

Answers (2)

KJEK-Code
KJEK-Code

Reputation: 705

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>

Upvotes: 2

phucbm
phucbm

Reputation: 893

This could be the solution. You currently have two animations that use the property transform altogether, what you need to do is separate them then the problem is easy peasy. I also add a paused/running state on hover for a little smoothness.

.foo {
  margin: auto;
  margin-top: 100px;
  padding: 1em;
  width: fit-content;
  border: solid 1px black;
  background: red;
  color: white;
  font-size: 2em;
  
  /* The infinite animation */
  animation: kf-hover 10s infinite;
  animation-play-state: paused;
}

.bar {
  /* The initial animation */
  animation: kf-initial 2s;
}

.foo:hover {
  animation-play-state: running;
}

@keyframes kf-initial {
  from {
    transform: scale(0.2)
  }
  to {
    transform: scale(1)
  }
}

@keyframes kf-hover {
  100% {
    transform: rotate(1turn)
  }
}
<div class="bar">
  <div class="foo">
    Hello world
  </div>
</div>

Upvotes: 3

Related Questions