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

Finish animation on hover even mouse leave

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.

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

#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>

>Solution :

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

$("#rotate").bind("webkitAnimationEnd mozAnimationEnd animationend", function(){
  $(this).removeClass("animated")  
})

$("#rotate").hover(function(){
  $(this).addClass("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.

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