CSS

Restart CSS Animation

Since CSS3 we have been able to add CSS animation to our elements, these are relatively easy to setup. An example of a simple CSS animation example is to fade in an element.

.fadein_element
{
    opacity: 0;
    animation: fadein ease-in 2s;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

To run this CSS animation all we have to do is add the .fade_element CSS class to an element.

<h1 class="fadein_element">Hello World</h1>

With the CSS class assigned to the H1 tag the browser will run this CSS animation on the page load event, but what if you want this animation on say a click event?

You will need to assign this CSS class to an element on the click event of a button, as soon as the class is assigned to the HTML element it will start the animation.

$('button').on('click', function(){
    $('h1').addClass('fadein_element');
});

The above code will run the animation and fade the element into the page, but what if you want to run this animation again on the same element. You would think that to run this animation again all you will need to to is remove the animation class from the element and re-add it.

$('button').on('click', function(){
    $('h1').removeClass('fadein_element').addClass('fadein_element');
});

Well this code doesn't work, the CSS animation will not restart. This doesn't work because the animation end event listener hasn't been activated on this element. If we were to change the animation on this event to something else it will work, but because we are reactivating the same animation without telling it that it has stopped it will not restart.

An easy way of restarting the animation is to replace the element with a new element which can be done by using the jQuery clone method with remove method.

$('button').on('click', function(){
    var heading = $('h1').clone().removeClass();
    $('h1').remove();
    $('header').append(heading);
    $('h1').addClass('fadein_element');
});

The above code will clone the H1 tags with the CSS classes removed, then it will remove the starting H1 tag, we can then add the cloned element back into the heading then finally add the animation class back onto the H1.

View the demo to see how these two buttons work.

Demo

Back to top