Home > Mobile >  How to keep an animation in its final state after removing the animation CSS class?
How to keep an animation in its final state after removing the animation CSS class?

Time:08-18

I am trying to rotate a square infinitely, but only when the mouse is moved. In order to get something like a "mouse stopped" event, I added a isMouseMoving variable which is true or false depending on whether the mouse is moving or not.

The class of the animation .spin is added with a svelte ternary operator depending on whether the isMouseMoving variable is true or false.

<script>
  let isMouseMoving = false;
  let timer;

  function handleMouseMove(_) {
    isMouseMoving = true;
    clearTimeout(timer);
    timer = setTimeout(handleMouseStop, 30); 
  };

  function handleMouseStop() {
    isMouseMoving = false;
  }
</script>


<main on:mousemove={handleMouseMove}>
  <section>
    <div ></div>
  </section>
</main>


<style>
.square {
  height: 50px;
  width: 50px;
  background: purple;
}

.spin {
  animation: spin 5s linear forwards;
}

@keyframes spin {
  from {
    transform:rotate(0deg);
  }
  to {
    transform:rotate(360deg);
  }
}
</style>

What works is that whenever the mouse is moved, the square spins. What doesn't work though is that when the animation is stopped, the square keeps its degree of rotation.

Right now, it will fall back to its initial state before the rotation.

I tried the forwards animation fill mode like suggested in this thread, however this isn't changing anything for me.

CodePudding user response:

animation-play-state: paused; works. Use another class to apply it.

let isMouseMoving = false;
let timer;
let square = document.querySelector(".square");

function handleMouseMove(_) {
  isMouseMoving = true;
  square.classList.add("spin")
  square.classList.remove("paused")
  clearTimeout(timer);
  timer = setTimeout(handleMouseStop, 30);
};

function handleMouseStop() {
  isMouseMoving = false;
  // square.classList.remove("spin")
  square.classList.add("paused")
}

document.addEventListener('mousemove', handleMouseMove)
.square {
  height: 50px;
  width: 50px;
  background: purple;
  
}

.spin {
  animation: spin 5s linear infinite;
}

.paused {
  animation-play-state: paused;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
<main>
  <section>
    <div ></div>
  </section>
</main>

  • Related