Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

CSS3 Reset Animation Requires Timeout (if set animation from external style sheet)

CSS3 Reset Animation Requires Timeout (if set animation from external style sheet)

Problem

I have a CSS Animation. I apply it to a span within my div element with class span. I apply it from an external style sheet:

.skill > span { width:100%; -moz-animation:anim-skill 2s ease-out; -webkit-animation:anim-skill 2s ease-out; }

.anim-skill {width:100%; animation:anim-skill 2s ease-out; -moz-animation:anim-skill 2s ease-out; -webkit-animation:anim-skill 2s ease-out; -o-animation:anim-skill 2s ease-out;}

@keyframes anim-skill { from {width:0px;} to  {width:100%} }

When I want to reset the animation during run time I do this:

var mySkill = document.querySelector('.skill');
var bar = mySkill.childNodes[0];
//make it "from" state
bar.style.animation = 'none';
mySkill.style.width = 0;

//make it run
setTimeout(function () {
    mySkill.style.width = '';
    bar.style.animation = '';
}, 20);

This is very hacky. Is there a way to reset the animation this without using setTimeout? Note: If my timeout is 10ms or less it doesnt work also.

Problem courtesy of: Noitidart

Solution

The problem is that you can not remove the class and set it again, without leaving the browser to render itself.

The non hacky way to do this is a little bit more sophisticated: make the animation remove itself

a quick and dirty implementation of this can be:

$(document).ready(function() {
    var ele = document.getElementById("test");

    ele.addEventListener( 'webkitAnimationEnd', 
    function( event ) { ele.className = ""; }, false );
})

This will remove the animation class from the element, when the animation finishes. Afterwards, you can set the class again, without problems

fiddle

Solution courtesy of: vals

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

CSS3 Reset Animation Requires Timeout (if set animation from external style sheet)

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×