CSS & Javascript Manual Keyframe Animation

Viewed 157

Say I have an animation defined in css like so:

@keyframes my-animation {
    0% {
        // effect here
    }

    ...

    100% {
        // effect here
    }
}

I can use it in a div like so:

#container {
    animation: my-animation 10s linear ;
}

Is there any way I can use javascript to programmatically set the percentage of the animation at any point instead? Something along the lines of:

function() {
    let container = document.getElementById('container');
    while (some condition && container.percentage < 100) {
        container.percentage += 10;  // Here I would like to set the animation percentage to one of the percentages defined in the keyframe animation
    }
}

This is so I don't have to explicitly set the duration of the animation beforehand as it is unknown at runtime. I should add that I am aware that it currently is not possible to retrieve the percentage value of an animation but perhaps there is a way to manipulate it?

EDIT: From what I understand from the comment by lupz:

.animation0 { /* 0% */

    }

.animation10 { /* 10% */

    }

...

.animation100 { /* 100% */

    }

Then I can change the class of the element to whichever percentage I need.

1 Answers

You can the JS animation API - Element.animate(), and then you can control the percentage (the offset property) directly via JS:

const container = document.querySelector('.container');

const animate = (offset = 1) => {
  const height = container.getBoundingClientRect().height;
  
  const animation = container.animate([
    {
      transform: 'translateY(0px)',
      offset: 0
    },
    {
      transform: `translateY(calc(100vh - ${height}px))`,
      offset
    }
  ], {
    duration: 1000,
  });
  
  if(offset > 0) {
    animation.finished
      .then(() => animate(offset - 0.1));
  }
};

animate();
html, body {
  margin: 0;
}

.container {
  width: 100px;
  height: 100px;
  background: silver;
}
<div class="container"></div>

Related