Joel A. Shinness
Joel A. Shinness

Reputation: 151

How can I start CSS3 Animations at a specific spot?

I'm using CSS3 Animations, and I want to be able to move to a specific spot in the animation. For instance, if the CSS looks like this (and pretend that I used all the proper prefixes):

@keyframes fade_in_out_anim {
  0% { opacity: 0; }
  25% { opacity: 1; }
  75% { opacity: 1; }
  100% { opacity: 0; }
}
#fade_in_out {
  animation: fade_in_out_anim 5s;
}

then I would like to be able to stop the animation, and move it to the 50% mark. I guess that the ideal JavaScript would look something like this:

var style = document.getElementById('fade_in_out').style;
style.animationPlayState = 'paused';

// Here comes the made up part...
style.animation.moveTo('50%'); // Or alternately...
style.animationPlayPosition = '50%';

Does anyone know of a way to make this happen (hopefully in Webkit)?

Upvotes: 15

Views: 6561

Answers (2)

Venkata Raju
Venkata Raju

Reputation: 5215

  1. Get the animation object affecting the element
  2. Get it's duration
  3. Set the Animation object's currentTime to half of the duration value (since you want to set the progress to 50%)
let anim = fade_in_out.getAnimations()[0];
let duration = anim.effect.getTiming().duration;  
anim.currentTime = duration / 2;

Upvotes: 2

Jose Rego
Jose Rego

Reputation: 450

We can use the animation-delay property. Usually it delays animation for some time, and, if you set animation-delay: 2s;, animation will start two seconds after you applied the animation to the element. But, you also can use it to force it to start playing animation with a specific time-shift by using a negative value:

.element-animation{
animation: animationFrames ease 4s;
animation-delay: -2s;
}

http://default-value.com/blog/2012/10/start-css3-animation-from-specified-time-frame/

Upvotes: 40

Related Questions