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.

1I1III1
  • 167
  • 2
  • 10
  • possible duplicate of [Get/set current @keyframes percentage/change keyframes](http://stackoverflow.com/questions/18006099/get-set-current-keyframes-percentage-change-keyframes) – Gildas.Tambo Feb 25 '15 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 – 1I1III1 Feb 25 '15 at 21:18
  • And if you are going to use an interval, it's probably better to use [window.requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) instead, so it updates when the page is repainted, rather than a time. That should solve the blurring problem at least. – 1I1III1 Feb 25 '15 at 21:45

1 Answers1

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>
vals
  • 61,425
  • 11
  • 89
  • 138