0

I was wondering if it was possible, using some javascript or jquery, to skip to the next, or go to the last part of a css animation. Lets say we have the following:

@keyframe effect{
    0%{opacity:1;}
    45%{opacity:1;}
    50%{opacity:0;}
    95%{opacity:0;}
    100%{opacity:1;}
}

that will fade something out and then back in

so lets say I made some buttons. How would I do the following:

$('#next').click(function(){
    //skip to the next animation part
});
$('#previous').click(function(){
    //skip to the previous animation part
});
Ryan Saxe
  • 17,123
  • 23
  • 80
  • 128

2 Answers2

1

It's not really possible unless you break the CSS into different parts based on classes and then add/remove classes.

However, there is an absolutely fantastic javascript library called Greensock, that allows timeline-based animation - and in many cases is faster than CSS animations. It also has the benefit of being cross-browser compatible.

If you were, for example to create something similar using Greensock, it would look something like this:

var effect = new TimelineMax({paused:true});

effect.addLabel('start');
effect.to(
  '#myItem',
  1,
  {css:{opacity:1}}
);
effect.addLabel('step1');
effect.to(
  '#myItem',
  1, 
  {css:{opacity:0}}
);
effect.addLabel('end');

effect.play();

$('#gotoEnd').on('click', function(e){
  e.preventDefault();
  effect.seek('end');
});
ahren
  • 16,803
  • 5
  • 50
  • 70
0

With the use of the animation-play-state Property, you can pause an animation and update the transform, then restart it.

element.style.webkitAnimationPlayState = "paused";
element.style.webkitAnimationPlayState = "running";

However you can't pause the animation, transform it, resume it, and expect it to run fluidly from the new transformed state.

At this time, there is no way to get the exact current "percentage completed" of a CSS keyframe animation. The best method to approximate it is using a setInterval or requestAnimationFrame.

This CSS tricks article explains this further, and gives an example of using setInterval. Another option is to use request animation frame

As mentioned GreenSock or Velocity are animation libraries which allow for extremely fast and smooth animations

svnm
  • 22,878
  • 21
  • 90
  • 105