javascripthtmlcsseventscss-animations

Why the elapsedTime property of animation event is undefined


I'm trying to access the elapsedTime property of animation events as shown in MDN.

When i inspect the object i can see the property with the corresponding value, However when i log it in console i'm getting undefined. Following is the sample code:

HTML

<div id='box'></div>

CSS

#box {
  position:absolute;
  top:0;
  left:0;
  width:50px;
  height:50px;
  background:red;
  animation: move 5s infinite;
}

@keyframes move {
  0% { left: 0; }
  50% { left:90%; }
  100% { left: 0;}
}

JS

$("#box").on("animationiteration webkitAnimationIteration", function (e) {
  console.log(e.elapsedTime); // this logs undefined
});

I've setup a fiddle here


Solution

  • The correct syntax is

    console.log(e.originalEvent.elapsedTime);
    

    In the javaScript event, the variable is elapsedtime, so you can access it as you did

    javascriptevent.elapsedTime

    However, you are setting the event function in jQuery. the jQuery event has a lot of the javascript variables mirrored, but not all.

    To access the javascript variables not mirrored in the jQuery event, you have the originalEvent object, that is the original javascript event, inside the jQuery event.

    So, the syntax is

    jQueryEvent.originalEvent.elapsedTime
    

    Use the same syntax to access all the variables not mirrored in the jQuery event