Is there a way to completely define CSS animation using only JavaScript?

I am looking to implement CSS animation on HTML elements that are generated entirely through a JavaScript function. The approach I am taking involves customizing settings and functions for each part of the animation, which is why this method is necessary. Defining the animation itself in JavaScript is not an issue:

element.style.animation = "sprite_anim 1.0s steps(4) infinite"

The challenge lies in defining the keyframes, as they typically require a static definition in a CSS file.

@keyframes sprite_anim {
    from {
        background-position: 0px 0px;
    }
    to {
        background-position: -128px 0px;
    }
}

In this scenario, I need the code to dynamically generate those 4 offset values as well; They will be set once per image, so it is acceptable to create a one-time animation for each combination I intend to use, but the values themselves are determined by a script. What is the most unobtrusive, cross-browser compatible, and concise way to define my keyframes within the code?

Answer №1

Regrettably, I am unable to respond to comments or indicate them as a solution: arieljuod provided the precise answer I was seeking above. What I had been searching for is the element.animate() method which achieves the same effect as CSS animation but entirely from JavaScript as needed.

https://developer.mozilla.org/en-US/docs/Web/API/Element/animate

Answer №2

If you only have a single set of keyframes defined in your CSS, such as:

@keyframes animation {
    from {
        transform: scale(1);
    }
    to {
        transform: scale(2);
    }
}

In JavaScript, you can dynamically adjust these values for each element by using

element.style.setProperty("--tox", newValueX)
, etc.

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

Using React JS to send an object as an argument to an action function

How do I pass the "fields" object to the action "createPost" after creating it with validation in a form? Do I need to use "props" or could it be related to the dispatcher line? import React, { Component } from 'react'; import Header from ' ...

While using axios to make a GET request, I encountered errors when checking for .isSuccess in react

const searchInvoiceList = async ( plantLocation: string, invoiceType: string ) => { let dataList: InvoiceData[] = []; await axios .get(`${linkURL}inv/getControlList/${plantLocation}/${invoiceType}`) .then((response) => { dataLis ...

`WebAuthn API allows for easy identification of fingerprints``

Google introduced WebAuthn https://developers.google.com/web/updates/2018/05/webauthn two years back. Is it possible to accurately identify the finger that a user registered or verified? For instance, the server could not only obtain the public key but a ...

Is it possible to utilize a variable from a Higher Order Function within a different generation function?

I am facing a dilemma with the need to utilize email = user.email in newcomment['comments/'+id] = {id,comment,email,date}. However, I am unable to incorporate email = yield user.email or yield auth.onAuthStateChanged(user => {email = user.em ...

Progressive JQuery Ajax Requests

I'm attempting to retrieve specific information from a webpage, such as the title of the page and the domain name, and then perform an asynchronous POST request using jQuery with that extracted data. However, I've encountered an issue where my Ja ...

Updating with MySQL can only manipulate integers and not strings

Setting up seems simple, but the number of potential causes is overwhelming for someone new to programming like me: In JavaScript, I define and later call: function dbUpdate(x, y, z) { $.ajax({ url: 'php/dbUpdate.php', type: ...

Angular is sending a parameter with a null value, which is not supposed to happen

My filtering system used to work well with a code that displayed items of specific status. However, I had to modify it to match a select input requirement. <ul id="dropdown-basic" *dropdownMenu class="dropdown-menu" role="menu" aria-labelledby="button- ...

Tips for Deselecting a Table Cell in React

I've been working on a table in React and I'm trying to implement a feature where clicking on a cell colors it, and clicking on another cell uncolors the previous one. So far, I've managed to color cells upon clicking but I'm stuck on h ...

Can this functionality be accomplished using only HTML and CSS, without relying on JavaScript?

Image for the Question Is it possible to create a zoom functionality using only HTML and CSS, without relying on JavaScript? I need this feature for a specific project that doesn't support JavaScript. ...

The input element extends beyond the boundaries of the container

When the text is too long, the input exceeds the boundaries of its parent container. I have been exploring ways to wrap the text within the element. I attempted using CSS properties like word-break and text-wrap, but unfortunately, none of them produced t ...

Click event not functioning in programmatically loaded HTML

I am facing an issue with a JSON file that contains the page content I am trying to load. The link within it appears as follows: <a data-ng-click='foo()'>Bar</a> When I load this page content into the HTML page: <p class="body" ...

Why is it that I am unable to properly encode this URL in node.js?

$node querystring = require('querystring') var dict = { 'q': 'what\'s up' }; var url = 'http://google.com/?q=' + querystring.stringify(dict); url = encodeURIComponent(url); console.log(url); Here is the re ...

Unable to access an HTML element using refs within the render() method

Currently, I am working on developing a graphics editor using ReactJS. One of the main components in my project is the Workspace component. This particular component is responsible for drawing objects on the canvas element. The Workspace component is imple ...

Displaying a banner at the bottom of a React page

I need to display a banner with the text "All items..." on every page. Currently, I have set the position attribute to fixed, but the banner is aligned to the left and I want it to be centered horizontally instead. Below is my code snippet: export const Ba ...

Enhance the dropdown menu by incorporating a caret icon

Click here for the image, I am trying to incorporate the Bootstrap caret class into my select dropdown menu. .select_menu{ font-size: 12px; outline: none; border: thin #ddd solid; -webkit-appearance: none; -moz-appearance: none; appearance: ...

How can I create a textbox in vue.js that only allows numeric input?

methods: { acceptNumber() { var x = this.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/); this.value = !x[2] ? x[1] : '(' + x[1] + ')' + x[2] + (x[3] ? '-' + x[3] : & ...

Creating a standalone static page in Wordpress showcasing the header, sidebar, and footer of the twenty fourteen template

I have created a static blank page containing my website's header, sidebar, and footer. However, I am trying to remove the 'style' that is being enforced by the CSS of my WordPress template on the page. Below is the code I am using: <?p ...

Object is not compliant with HTMLInputElement interface and cannot execute 'stepUp'

Currently, I am facing an issue with passing the selected value from a dropdown list of countries to a PHP file using AJAX. The goal is to take this value and then transfer it to another input field identified by the ID #tele. Here is the gist of my code: ...

Having issues with ajax posting functionality

Is the following form correct? <form> <input type="submit" value="X" id="deleteButton" onclick="ConfirmChoice(<?php echo $id; ?>)" /> </form> Here is the function associated with the form: <script type='text/javasc ...

What is the best way to pass values from PHP to an HTML tag?

My initial HTML document includes a form with radio buttons. I want my second PHP file to display a message based on the user's selection, and include some formatting such as text size and color. file.html: <html> <body> <form action ...