Injecting dynamic CSS keyframes via JavaScript to introduce variability into animations

As I venture into the world of JavaScript as a beginner, I'm working on creating a simple game. In this game, there are pieces of 'rubbish' (represented by divs) floating from right to left down a river. The goal is for the player to click on the div and make it disappear.

However, I've hit a roadblock in adding randomness to the animation. I want each piece of rubbish to take a different path instead of following a fixed trajectory.

I had an idea to introduce a random value into the 'top' percentages of the keyframe animation. Here's a snippet of what I have so far - any suggestions on how to improve it? I wouldn't mind shifting all the animation logic 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%;}
            `
    

HTML


        <div class="game box"> 
            <div class="smallrubbish"></div> 
        </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%;}
        }
    

Answer №1

One interesting problem to tackle is generating random keyframes for CSS animations and loading them dynamically.

You can't directly add @keyframes definitions inline to an element, but you can change the animation name of an element programmatically by:

el.style.animationName = 'animation'

Furthermore, you can inject style elements into the document's head at runtime. To demonstrate this, let's take a basic example provided in the question where we randomly assign y values to an animation and animate a piece of rubbish:

const head = document.getElementsByTagName('head')[0];
const btnRubbish = document.querySelector('div.smallrubbish');

let keyframes = 
    `@keyframes rubbish {
   0%  {top:` + (Math.random() * 100) + `%; left: 100%;}
  50%  {top:` + (Math.random() * 100) + `%; left: 50%;}
 100%  {top:` + (Math.random() * 100) + `%; left: 0%;}`;
 
let style= document.createElement('STYLE');
style.innerHTML = keyframes;
head.appendChild(style);

btnRubbish.style.animationName = 'rubbish';
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;
}
<div class="game box"> 
<div class="smallrubbish"></div> 
</div>

This approach allows us to generate varying numbers of frames with different % values and x-axis positions for the animation, always moving from right to left. Each piece of rubbish could also have its own unique animation-duration.

The challenge lies in managing the dynamically added styles and assigning new ones to each piece of rubbish. This becomes particularly crucial in complex game scenarios where resources may be limited. Keeping track of the elements and keyframes created enables efficient reuse or removal when no longer necessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for attaching my navigation bar to the top of the webpage

Can anyone assist me in fixing the top portion of my webpage so that it stays in place? I attempted to use the position:fixed attribute, but this caused issues as my content started overlapping with the fixed divs. You can find my website here: www.croo ...

Having trouble toggling classes with mouseup in Wordpress Underscores theme

While I'm utilizing Underscores as the foundation theme for my website, one aspect that I particularly appreciate is its incorporation of a functional mobile navigation component. However, since my site is essentially single-page, the navigation remai ...

Challenges encountered while creating a Number Tables Program (such as displaying 12 x 1 = 12) using Javascript

Currently, I am working on developing a program that can generate mathematical tables for any given number. For example: 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 To achieve this, the user should provide the following inputs: (1) The number they want ...

Display a div when a specific moment in the video is reached and then conceal it at a different

I'm attempting to display a div at a specific time during a video and have it disappear 2 seconds later. However, the current code I've tried is not producing the desired result: $(document).ready(function() { $("#element_1").hide(); document ...

Having trouble implementing the center edge effect in this CSS design

Looking for help with CSS to center the edges of a family tree design. Has anyone experience in working on styling family trees? *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .tree { ...

Utilizing Chessboard Positions in an if-else Statement with the Chessboard.js Library

I have been attempting to develop a function that utilizes an if-statement to verify whether a chessboard is positioned in a specific arrangement (the one I am using as the starting position) with the assistance of the chessboard.js library I experimented ...

Utilize Google API V3 to create a dropdown selection list of locations, extracting latitude and longitude values from a JSON text file

I am working on creating a map using Google Maps API v3. I have implemented a dropdown select list for different places and I am pulling the latitude and longitude values from it. Initially, I manually added the options like this: <option value= ...

Tips for effectively utilizing the display:none property to conceal elements and permanently eliminate them from the DOM

While working on my website, I utilized CSS media queries to hide certain elements by using display: none. Even though this effectively hides the element from view, it still lingers in the DOM. Is there a way to completely eliminate the element from the ...

Once the PHP page loads, it becomes challenging for me to dynamically change values in JavaScript

Within my code snippet below, I am aiming to modify the initial value using a slider. The slider appears to be functioning correctly; however, it is not updating the values of timeout as indicated beneath the line $('ul.<?php echo $this->session ...

Creating an HTML table from an array of objects: A step-by-step guide

Is there a way to create an HTML table from an array of objects? I attempted the following code but encountered an object error: data: [{ "slot": "10:00-11:00", "isBooked": false }, { "slot": "11:00-12:00", "isBooked": false }, { "slot": "12:00-13:00", " ...

Inspecting element value on a website

On a marketplace website, I extracted the attribute (capacity_gold) from a table. Since the values are dynamic and constantly changing, I aim to develop a basic script that will notify me when the attribute value exceeds 100. The current value of the attr ...

center a horizontal line using StyledSheets in your project

After drawing a horizontal line, I noticed that it is positioned towards the left side of the screen. I am hesitant to increase its width. Are there any other methods to move it to the center? I attempted wrapping it with another view and using alignConten ...

Unlocking the Secrets: Adding Multiple Contents to Your Master Page in ASP

I need some clarification on a dilemma I'm facing. My master page has a content placeholder that is used by all subpages: <%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="SiteMaster" %> <!DOCTYPE html> ...

Implement a variety of HTTP response codes for a REST endpoint

I'm currently utilizing express to serve the REST API endpoints for a simulated backend. One of the endpoints requires the ability to return different HTTP response codes, while maintaining a 200 status for the other endpoints. Here is a snippet of my ...

Issue with close request on dialog box

Whenever an icon is clicked, a dialog box containing a form should appear. The purpose of this dialog box is to either add a new tab or delete a specific tab. In my implementation, I used ReactJS, Redux, and Material-UI for building the components. Even th ...

Is this code in line with commonly accepted norms and standards in Javascript and HTML?

Check out this Javascript Quiz script I created: /* Jane Doe. 2022. */ var Questions = [ { Question: "What is 5+2?", Values: ["7", "9", "10", "6"], Answer: 1 }, { Question: "What is the square root of 16?", Values: ["7", "5", "4", "1"], Answer: ...

Attempting to iterate through a JSON object containing nested objects and arrays of objects

For hours, I've been struggling to navigate through this json file with no success. When I log the data, it shows that Response is an Object, data is also an object, and saleItemCategories is an array containing four objects. The first object in the ...

JS and its dynamic color changes

A game has been developed using JavaScript and HTML. The game features a table with cells that are assigned IDs for toggling colors using an onClick function. The objective is simple: when a cell is clicked, all neighboring cells, including the clicked one ...

Troubleshooting a shadow mapping problem in three.js involving a ShaderMaterial that alters the positions of vertices

Within my current project, I have implemented a ShaderMaterial to depict terrains. The positions of the vertices are adjusted in the vertex shader based on information from a height map texture: vec4 mvPosition = modelViewMatrix * vec4( position + normal ...

Is there a way to retrieve the JavaScript variable name for a rhandsontable displayed in a Shiny application?

My project involves using the rhandsontable package to generate dynamic tables within a Shiny app. I am in need of a solution that allows me to select certain cells programmatically, triggered by specific user interactions. Unfortunately, I have not been ...