Finish animation on hover even mouse leave

Viewed 211

I'm using CSS keyframes to rotate an element on its hover state.

How do I make the element finish its animation even the mouse leave the element before it actually end?

For example, if I move my mouse out of the element(stop hovering) while the element only rotating to 180 degree (the full animation is 360 degree), it immediately stop the animation and go back to its original state instead of finish the animation.

#rotate {
  width: 120px;
  height: 120px;
  background-color: orange;
}

#rotate:hover {
  animation: rotating 1s ease 0s 1 normal forwards;
}

@keyframes rotating {
  0% {
    transform: rotate(0);
  }

  100% {
    transform: rotate(360deg);
  }
}
<div id="rotate"></div>

2 Answers

You need to use Javascript for this, the following snippet is shown using some jQuery, a working example:

$("#rotate").on({
   mouseenter() {
      $(this).addClass("animated"); 
   },
   animationend() {
      $(this).removeClass("animated");  
   },
});
#rotate {
  width: 120px;
  height: 120px;
  background-color: orange;
}

.animated {
  animation: rotating 1s ease 0s 1 normal forwards;
}

@keyframes rotating {
  0% {
    transform: rotate(0);
  }

  100% {
    transform: rotate(360deg);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="rotate"></div>

Make sure that the class animated is with the animation, and #rotate is the box you want to spin.

This worked for my situation as it pauses and starts from where it left off. For simple rotation, this feels nicer than the jump you usually get from hovering in and out.

@keyframes rotate {
    0% {
transform: rotate(0deg);
    }
    100% {
transform: rotate(360deg);
    }
}

.name-star {
    right: 5px;
    top: 15px;
    animation: 5s rotate infinite;
    animation-play-state: paused;
    animation-timing-function: ease-in;
}

.mat-grid-tile:hover .name-star {
    animation-play-state: running;
}
Related