Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I detect with JavaScript where we are percentage wise in a CSS Keyframe animation

I was thinking. I know I can detect when a CSS animation has started, finished or is repeated by listening for the animationstart, animationiteration, animationend events (obviously we are missing browser prefixes there), for example:

document.getElementById('identifier')
        .addEventListener("animationstart", function(){
          // do something...
        });

but I was wondering, is it possible to determine where we are are running a CSS animation, how for example with the following could I listen for when we are at 50% of the keyframe animation:

<!DOCTYPE html>
<html>
<head>
<style>
#animateDiv {
    width: 100px;
    height: 100px;
    background-color: red;
    position: relative;
    animation-name: example;
    animation-duration: 4s;
}

@keyframes example {
    0%   {background-color:red; left:0px; top:0px;}
    25%  {background-color:yellow; left:200px; top:0px;}
    50%  {background-color:blue; left:200px; top:200px;}
    75%  {background-color:green; left:0px; top:200px;}
    100% {background-color:red; left:0px; top:0px;}
}
</style>
</head>
<body>
<div id="animateDiv"></div>
<script>
// what do I do here? How do I listen for the 50% event of the keyframes?
document.getElementById('animateDiv').addEventListener('animation at 50%?', function() {
 console.log('got it');
})
</script>
</body>
</html>
like image 726
Mike Sav Avatar asked Jul 20 '16 11:07

Mike Sav


People also ask

What is the keyframe selector to equivalent to as a percentage?

Inside each @keyframes rule is a list of percent values or the keywords to and from. The keyword from is equivalent to 0%, and the keyword to is equivalent to 100%.

Does CSS animation use JavaScript?

CSS allows animation of HTML elements without using JavaScript or Flash! In this chapter you will learn about the following properties: @keyframes.

Is it better to animate with CSS or JavaScript?

In summary, we should always try to create our animations using CSS transitions/animations where possible. If your animations are really complex, you may have to rely on JavaScript-based animations instead.

How many percentages can you define in a keyframes rule?

keyframes-selector: The keyframes-selector defines the percentage of the animation. It lies between 0% to 100%. One animation can contain many selectors.


2 Answers

Ello, mate. I dont know if you can get the exact keyframe from a CSS animation, but u can use some mathemathics to get it, like our mate Paulie_D suggested.

On your code, your animation is 4s length, so, the keyframe 50% of the annimation is after 2s:

//......
//when the animation starts....
setTimeout(function(){
      //Enter your stuff here
}, 2000); //2 seconds delay, considering your animation length = 4s;

You can also use (needs jQuery):

$("#animated_element").bind("half_animation", function(){
      //Ya stuff here
});
//.........
//When the animation starts...
setTimeout(function()
{
     $("#animated_element").trigger("half_animation");
}, 2000);

Or:

$("#animated_element").bind("half_animation", function(){
      once = 0;
      setTimeout(function()
      {
           //Ya stuff here....
      }, 2000)
});
//........
//When the animation starts
$("#animated_element").trigger("half_animation");

I hope it help ya, mate.

like image 167
Vini Antichrist Avatar answered Oct 07 '22 18:10

Vini Antichrist


G'day mate. Here's my take on it.

  1. Get the animation duration.
  2. Sprinkle some mathematics on it like Vini suggested.
  3. setTimeout()

Code:

const fn_runAtKeyframe = (DOMElement, keyframe, callback) => {
  const animationDuration = window.getComputedStyle(DOMElement).animationDuration;
  // animationDuration returns string, e.g. "5s" or "500ms", so need to parseInt()
  // if it is in seconds, change it to milliseconds
  let animationKeyframe
  if (animationDuration.replace(/[0-9]/g, '') === "s") {
    animationKeyframe = parseInt(animationDuration) * keyframe * 1000
  } else {
    animationKeyframe = parseInt(animationDuration) * keyframe
  }

  const doStuff = (e) => {
    setTimeout(() => {
      console.log(`Function "${callback.name}" will run at ${keyframe*100}% keyframe`)
      callback();
    }, animationKeyframe)
  }
  DOMElement.addEventListener("animationstart", doStuff); 
  // or use "animationiteration" depending on your usecase
}

Run it,

const animateDiv = document.querySelector("#animateDiv")
const keyframe = 0.5 // at 50% keyframe
const callback = () => {
  // do stuff here...
};
fn_runAtKeyframe(animateDiv, keyframe, callback)
like image 35
Andy Fazulus Avatar answered Oct 07 '22 18:10

Andy Fazulus