4

Is it possible to get which stage of a CSS transition an object is in with Javascript, without the use of a interval, or relying on a starting timestamp? I know that transitions can be strung together, but I'd rather avoid that if I can.

For example for a div going through the following transition:

@keyframes example {
  0% {background: red;}
  50% {background: blue;}
  100% {background: yellow;}
}

Is it possible to find if the div is between 0% and 50%? Pure Javascript please.

3
  • possible duplicate of Get/set current @keyframes percentage/change keyframes Commented Feb 25, 2015 at 19:47
  • I'd rather avoid the use of an interval, as suggested in the answer, seeing as it can get off sync if the machine is slow or if the page is blurred Commented Feb 25, 2015 at 21:18
  • And if you are going to use an interval, it's probably better to use window.requestAnimationFrame instead, so it updates when the page is repainted, rather than a time. That should solve the blurring problem at least. Commented Feb 25, 2015 at 21:45

1 Answer 1

2

You can assign a property in the animation and retrieve this property value to know the animation stage. For instance, asign z-index a value between 100 and 200:

click the element to show the percentage of the animation

function showStep () {
    var ele = document.getElementById("test");
    var step = getComputedStyle(ele).getPropertyValue("z-index") - 100;
    ele.innerText = step;
}
#test {
  position: absolute;
  width: 400px;
  height: 200px;
   border: solid red 1px;
   -webkit-animation: colors 4s infinite;
   animation: colors 6s infinite;
  font-size:  80px;
  color:  white;
}


@-webkit-keyframes colors {
  0% {background: red; z-index: 100;}
  50% {background: blue;  z-index: 150;}
  100% {background: yellow; z-index: 200;}
}

@keyframes colors {
  0% {background: red; z-index: 100;}
  50% {background: blue;  z-index: 150;}
  100% {background: yellow; z-index: 200;}
}  
<div id="test" onclick="showStep();">
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

For what is worth, getComputedStyle() is only supported in IE9+
@JFK But animations aren't supported in IE8, So this is not a problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.