I have a document with multiple CSS animations and I need to get the total running length that can be seen in chrome dev tools (Animations timeline) as per screenshot
I have thought of a few ways but not sure what's 1. the most accurate and 2. most efficient
PS the CSS animation classes are added dynamically on load so sometimes it maybe longer and other times shorter
FYI I have considered using JS document.getAnimations() to get an array but not sure where to go from there since they all have similar:
array:

start time and current time
end total value:

I think you can get this using a combination of the animationstart and animationend events. Here's a modified version of MDN's example, here using two different elements that we start the animation on at random times:
const activeElements = new Map();
function handleAnimationStart({target}) {
const now = Date.now();
console.log(`Started on ${target.getAttribute("data-label")} at ${now}`);
activeElements.set(target, now);
}
function handleAnimationEnd({target}) {
const now = Date.now();
const start = activeElements.get(target);
if (typeof start === "number") {
activeElements.delete(target);
console.log(`Ended on ${target.getAttribute("data-label")} at ${now}, duration = ${now - start}`);
}
}
function startAnimation(element) {
element.classList.toggle("active");
element.addEventListener("animationstart", handleAnimationStart);
element.addEventListener("animationend", handleAnimationEnd);
}
const elements = document.querySelectorAll("p.animation");
setTimeout(() => {
startAnimation(elements[0]);
}, Math.floor(Math.random() * 1000));
setTimeout(() => {
startAnimation(elements[1]);
}, Math.floor(Math.random() * 2000));
.container {
height: 3rem;
}
.event-log {
width: 25rem;
height: 2rem;
border: 1px solid black;
margin: 0.2rem;
padding: 0.2rem;
}
.animation.active {
animation-duration: 2s;
animation-name: slidein;
}
@keyframes slidein {
from {
transform: translateX(100%) scaleX(3);
}
to {
transform: translateX(0) scaleX(1);
}
}
<div class="animation-example">
<div class="container">
<p class="animation" data-label="0">You chose a cold night to visit our planet.</p>
</div>
<div class="container">
<p class="animation" data-label="1">You chose a cold night to visit our planet.</p>
</div>
</div>