Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart animation in CSS3: any better way than removing the element?

Tags:

javascript

css

I have a CSS3 animation that needs to be restarted on a click. It's a bar showing how much time is left. I'm using the scaleY(0) transform to create the effect.

Now I need to restart the animation by restoring the bar to scaleY(1) and let it go to scaleY(0) again. My first attempt to set scaleY(1) failed because it takes the same 15 seconds to bring it back to full length. Even if I change the duration to 0.1 second, I would need to delay or chain the assignment of scaleY(0) to let the bar replenishment complete. It feels too complicated for such a simple task.

I also found an interesting tip to restart the animation by removing the element from the document, and then re-inserting a clone of it: http://css-tricks.com/restart-css-animation/

It works, but is there a better way to restart a CSS animation? I'm using Prototype and Move.js, but I'm not restricted to them.

like image 750
Leo Avatar asked Jun 07 '11 16:06

Leo


People also ask

How do you repeat an animation in CSS?

The animation-iteration-count property in CSS is used to specify the number of times the animation will be repeated. It can specify as infinite to repeat the animation indefinitely.

Which CSS property is used to play animation again and again?

The animation-play-state property specifies whether the animation is running or paused.


2 Answers

No need in timeout, use reflow to apply the change:

function reset_animation() {    var el = document.getElementById('animated');    el.style.animation = 'none';    el.offsetHeight; /* trigger reflow */    el.style.animation = null;   }
#animated {    position: absolute;    width: 50px; height: 50px;    background-color: black;    animation: bounce 3s ease-in-out infinite;  }  @keyframes bounce {    0% { left: 0; }    50% { left: calc( 100% - 50px ); }    100% { left: 0; }  }
<div id="animated"></div>  <button onclick="reset_animation()">Reset</button>
like image 136
user Avatar answered Oct 06 '22 00:10

user


Just set the animation property via JavaScript to "none" and then set a timeout that changes the property to "", so it inherits from the CSS again.

Demo for Webkit here: http://jsfiddle.net/leaverou/xK6sa/ However, keep in mind that in real world usage, you should also include -moz- (at least).

like image 41
Lea Verou Avatar answered Oct 05 '22 22:10

Lea Verou