css3 animation on :hover; force entire animation

I'm afraid that the only way to solve this is with a bit of javascript, you must add the animation as a class and then remove it when the animation finishes.

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

$(".box").hover(function(){
  $(this).addClass("animated");        
})

http://jsfiddle.net/u7vXT/


Same answer with @methodofaction but for anyone using React:

import React, { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

export default function Icon({ icon }) {
    const [animated, setAnimated] = useState(false);

    return (
        <div
            onMouseEnter={() => setAnimated(() => true)}
            onAnimationEnd={() => setAnimated(() => false)}
        >
            <FontAwesomeIcon icon={icon} className={animated ? 'animated' : ''} />
        </div>
    );
}

I created a JsFiddle with this answer from the same post https://stackoverflow.com/a/7697786/8335898 using pure Javascript if anyone wants to use it.

const elements = document.getElementsByClassName('box');

for (let i = 0; i <= elements.length; i++) {
  elements[i].addEventListener('animationend', function(e) {
    elements[i].classList.remove('animated');
  });

 elements[i].addEventListener('mouseover', function(e) {
   elements[i].classList.add('animated')
 })
}

just to improve Duopixel answer, when runnig infinite animitation I have to do:

$(".box").css("animation-iteration-count", "1"); 
$(".box").bind("webkitAnimationEnd mozAnimationEnd animationEnd", function(){
  $(this).removeClass("animated")  
})
$(".box").hover(function(){
  $(".box").css("animation-iteration-count", "infinite"); 
  $(this).addClass("animated");        
})

This just not abruptly end the animation.

Tags:

Css

Animation