I am trying to toggle an animation on an element using the CSS Web Animations API (WAAPI). Specifically, I want the animation to transition smoothly between two states on each button click — essentially playing forward on the first click, then reversing on the second, and so on.
I’ve set up my keyframes and options correctly, and the animation runs fine the first time, but from the second toggle onward, the animation becomes jittery and visually “janky”.
!Important! I also want the box to get the end of animation styles.
I want the animation to respond correctly even when the user clicks the button rapidly, ensuring that it reverses immediately from its current state without any delay or visual glitches.
Here is a link to code pen where I was replicated the issue: https://codepen.io/mab141211/pen/VYYoOjw
const keyframes = [
{ border: '2px solid red', width: '200px', backgroundColor: 'blue', offset: 0, },
{ border: '6px solid green', width: '250px', backgroundColor: 'purple', offset: 1, },
];
// Options
const options = {
duration: 200,
easing: 'ease-in',
fill: 'both',
};
let isPlayingForward = true;
const animation = box.animate(keyframes, options);
animation.pause();
button.addEventListener('click', () => {
if (isPlayingForward) {
animation.play();
} else {
animation.reverse();
}
isPlayingForward = !isPlayingForward;
});```