Search code examples
csscss-animations

Run CSS3 animation only once (at page loading)


I'm making a simple landing page driven by CSS3. To make it look awesome there's an <a> plopping up:

@keyframes splash {
    from {
        opacity: 0;
        transform: scale(0, 0);
    }
    50% {
        opacity: 1;
        transform: scale(1.1, 1.1);
    }
    to {
        transform: scale(1, 1);
    }
}

And to make it even more awesome I added a hover animation:

@keyframes hover {
    from {
        transform: scale(1, 1);
    }
    to {
        transform: scale(1.1, 1.1);
    }
}

But there comes the problem! I assigned the animations like this:

a {
    /* Some basic styling here */

    animation: splash 1s normal forwards ease-in-out;
}
a:hover {
    animation: hover 1s infinite alternate ease-in-out;
}

Everything works just fine: The <a> splashes into the users face and has a nice vibration when he hovers it. Bit as soon as the user blurs the <a> the smooth stuff ends abruptly and the <a> repeats the splash-animation. (Which is logical to me, but I don't want it to) Is there some way to solve this problem without some JavaScript Class Jiggery Pokery?


Solution

  • After hours of googling: No, it's not possible without JavaScript. The animation-iteration-count: 1; is internally saved in the animation shothand attribute, which gets resetted and overwritten on :hover. When we blur the <a> and release the :hover the old class reapplies and therefore again resets the animation attribute.

    There sadly is no way to save a certain attribute states across element states.

    You'll have to use JavaScript.