Dynmatically adding CSS keyframe from JS to add randomness to animation

To aid my newbie journey into JS I'm trying to make a simple game - where there are pieces of 'rubbish' (divs) floating from right to left down a river, then when a player clicks the div it disappears.

I'm stuck trying to add randomness to the animation, so each piece of rubbish will take a different path.

I was hoping there would be a way to pass a random value into the 'top' percentages of the keyframe animation, something like this - any ideas how it could be adapted? I wouldn't mind all the animation being placed into JS

const btnRubbish = document.querySelector('div.smallrubbish')
const x = (Math.random() * 100)

btnRubbish.style.transform = 
    `@keyframes rubbish {
   0%  {top: ${x}%; left: 100%;}
  50%  {top: ${x}%; left: 50%;}
 100%  {top: ${x}%; left: 0%;}`


<div class="game box"> 
<div class="smallrubbish"></div> 

Relevant CSS

div.smallrubbish {
  display: block;
  height: 50px;
  width: 50px;
  background-color: rgba(255, 124, 0, 1);
  border-radius: 100%;
  position: absolute;
  top: 50%;
  left: 100%;
  animation-name: rubbishflow;
  animation-duration: 8s;
  animation-timing-function: linear;
  animation-iteration-count: 1;
  animation-delay: 0s;
  animation-fill-mode: forwards;

@keyframes rubbishflow {
   0%  {top: 50%; left: 100%;}
  50%  {top: 25%; left: 50%;}
 100%  {top: 60%; left: 0%;}

Read more here: https://stackoverflow.com/questions/64946143/dynmatically-adding-css-keyframe-from-js-to-add-randomness-to-animation

Content Attribution

This content was originally published by Hannah_W at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: