Hugo Giusti
Hugo Giusti

Reputation: 197

Looping CSS3 transition

I'm trying to loop a CSS3 transition, the idea is to add a class to the element to start the transition and listen to the transitionend event, when the event is fired I remove the class and start again.

var transition = function () {
    // add class to start the transition
    flipper.addClass('flipped');

    flipper.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {
        // remove class when transition is done
        flipper.removeClass('flipped');
        transition();
    });
}

Here is a fiddle with the code

The problem is that it only runs the first time, when the class is added a second time the event is never fired.

Is there any other way to loop a transition?

Upvotes: 2

Views: 198

Answers (1)

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

The browser is not getting chance to remove the class before you add it again, so it's not resetting the style. Putting a 1ms delay in fixes it...

flipper.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function () {
    // remove class when transition is done
    $('#console').append('[removing class]');
    flipper.removeClass("flipped");
    setTimeout(function() {
        transition();
    }, 1);
});

Modified jsFiddle link

Note:

You could pass transition as a parameter to the timeout call, like this...

setTimeout(transition, 1);

It's just a habit of mine to do it as I have above.

Upvotes: 5

Related Questions