Javascript DOM AnimationEvent elapsedTime Property

Introduction

Find out how many seconds an animation has been running:

This example uses the addEventListener() method to attach an "animationstart" and "animationiteration" event to a DIV element.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {//from w w w. ja  v a  2  s . com
  margin: 25px;
  width: 550px;
  height: 100px;
  background: orange;
  position: relative;
  font-size: 20px;
  text-align: center;
  -webkit-animation: mymove 4s infinite; /* Chrome, Safari, Opera */
  animation: mymove 4s infinite;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes mymove {
  from {top: 0px;}
  to {top: 200px;}
}

@keyframes mymove {
  from {top: 0px;}
  to {top: 200px;}
}
</style>
</head>
<body>
<div id="myDIV">The animation has started</div>

<script>
var x = document.getElementById("myDIV");
// Code for Chrome, Safari and Opera
x.addEventListener("webkitAnimationIteration", myRepeatFunction);
// Standard syntax
x.addEventListener("animationiteration", myRepeatFunction);

function myRepeatFunction(event) {
  this.style.backgroundColor = "lightblue";
  this.innerHTML = "Elapsed time: " + event.elapsedTime + " seconds";
}
</script>

</body>
</html>

The elapsedTime property returns the number of seconds an animation has been running, when an animation event occurs.

The return value is not affected if the animation is paused by using the animation-delay CSS property.

For the animationstart event, this property always returns "0".

This property is read-only.




PreviousNext

Related