Yaniv
Yaniv

Reputation: 164

How to pause a css animation, and then continue running from the pause point?

I'm playing a CSS animation with infinite iterations, until some point I pausing it from java script (using technique from here).

At later time I resume the animation. The problem is that the animation is restarting from the beginning point, and not from the last point before the pause.

Does there is a way to continue the animation from the pause point, without jumping to the start?

Edit: Between the pause and resume I also change the animation duration, see the demo. You should see some 'jumping'. Need explanation about this strange behavior.

Upvotes: 4

Views: 4277

Answers (2)

Christofer Vilander
Christofer Vilander

Reputation: 18022

I've just started to dig into JS myself, so there are surely better ways to do this, but how about something like this - Demo (Unprefixed version).

CSS

#box {
    position: relative;
    top: 20px;
    left: 20px;
    width: 100px;
    height: 100px;
    background: #393939;
    animation: move 2s linear infinite;
    animation-play-state: running;
}

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

JS:

(function () {

    var box = document.getElementById('box');

    box.onclick = function () {

        if (box.style.animationPlayState === "paused") {
            box.style.animationPlayState = "running";

        } else {
            box.style.animationPlayState = "paused";
        }

    };
})();

Based on if the animation is running or paused I change the animation-play-state onclick.

EDIT: Added the css code.

Upvotes: 1

Fly_pig
Fly_pig

Reputation: 165

http://jsfiddle.net/zhang6464/MSqMQ/

Just switch animation-play-state css property to be paused, according to the article you supplied(http://css-tricks.com/restart-css-animation/

Upvotes: 1

Related Questions