Javascript Get Element CSS Transition Step

Is it possible to get at what stage of CSS transition the object is with Javascript, without using an interval, or rely on the starting timestamp? I know that transitions can be pulled together, but I would prefer to avoid this 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 determine if a div is between 0% and 50%? Pure Javascript please.

+4
source share
1 answer

You can assign a property in the animation and get this property value to find out the stage of the animation. For example, asign z-index a value from 100 to 200:

click an item to show animation percentage

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>
Hide result
+2

All Articles