I’m trying to make a CSS animation that bounces back and forth, with a pause at each end. Using the Javascript method element.animate() seems to do the trick, except that using keyframes breaks the easing function, which doesn’t happen when using only CSS.
Am I using animate() wrong? Is it a bug? Why do Javascript and CSS behave differently? The animate MDN docs don’t say anything about this.
<div id="animation">Ball</div>
window.onload = function() {
element = document.getElementById("animation")
const anim = element.animate(
[
{ offset: 0, transform: "translateX(0)" },
{ offset: 0.1, transform: "translateX(0)" },
{ offset: 0.9, transform: "translateX(10vw)" },
{ offset: 1, transform: "translateX(10vw)" },
],
{
duration: 5000,
easing: "ease-in-out",
direction: "alternate",
iterations: Infinity,
}
);
}
Creating the same animation in CSS works with the correct easing.
#animation {
animation-name: move;
animation-direction: alternate;
animation-duration: 5s;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
}
@keyframes move {
from {
transform: translateX(0);
}
10% {
transform: translateX(0);
}
90% {
transform: translateX(10vw);
}
to {
transform: translateX(10vw);
}
}
However, I can’t use CSS because I want the keyframe percentages/offsets to be changed programmatically.
Fernandossmm is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.