htmlcsswebkitcss-animationswebkit-animation

Webkit Keyframes on Hover - Prevent Previous Animation


I have an element that I have a set of @-webkit-keyframes to animate in. On page load, these keyframes run, and the intro looks great.

Next, I have a second set of @-webkit-keyframes on hover and set to repeat, so on hover, that element has a looping animation. That also works great.

However, the instant I move the mouse away from the element, the first (intro) set of keyframes gets run again. I don't want it to run after it first runs. Is there an easy way to prevent this in CSS?

Minimal example of what I have

#e { -webkit-animation: fadeIn 1s ease-out 0.5s; } /* Fades in on load, BUT gets called when mouse moves away as well */
#e:hover { -webkit-animation: pulse 1s ease-in-out 0s infinite alternate; } /* Works fine, pulses on hover */

Also, can someone with 1500+ reputation edit the tags and add the webkit-animation tag? I can't believe it hasn't been created yet… :\


Solution

  • There is no pure CSS way of accomplishing what you need. You can add the animation to a parent element or to a wrapper and animate each element separately:

    .wrapper {
        -webkit-animation: fadeIn .5s ease-out 0 1;
    }
    #e { 
        width: 100px;
        height: 100px;
        background-color: #000;
    }
    #e:hover { 
        -webkit-animation: pulse 100ms ease-in-out 0s infinite alternate; 
    } 
    @-webkit-keyframes fadeIn {
            0%   { opacity: 0; }
            100% { opacity: 0.5;}
    }
    
    @-webkit-keyframes pulse {
            0%   { background-color: #000; }
            100% { background-color: #c00; }
    }
    

    http://jsfiddle.net/3PuT2/