Is there a way to dynamically adjust @keyframes properties through JavaScript?

I am looking to dynamically change the top value of the keyframes based on a JavaScript variable x.

While I have experience changing CSS with JavaScript, this particular challenge has me stumped.

Code:

var x = Math.floor((Math.random() * 1080) + 1);
div {
    width: 100px;
    height: 100px;
    background-color: red;
    position: relative;
    -webkit-animation-name: example; /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: 4s; /* Safari 4.0 - 8.0 */
    animation-name: example;
    animation-duration: 4s;
}


@keyframes example {
    0%   {left:0px; top:300px}
    100% {left:830px; top:0px}
}
 <div></div>

Answer №1

Utilize CSS variables for a simple solution:

let y = Math.floor((Math.random() * 200) + 1);
console.log(y);
let rootElm = document.querySelector(':root');
rootElm.style.setProperty("--topVal",y+"px");
:root {
  --topVal: 0;
}

div.container {
  width: 80px;
  height: 80px;
  background-color: blue;
  position: absolute;
  -webkit-animation-name: moveElement;
  /* Chrome, Safari, Opera */
  -webkit-animation-duration: 3s;
  /* Chrome, Safari, Opera */
  animation-name: moveElement;
  animation-duration: 3s;
}

@keyframes moveElement {
  0% {
    top: var(--topVal);
  }
  100% {
    top: 0;
  }
}
<div class="container"></div>

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

Retrieve the value of an object from a string and make a comparison

var siteList = {}; var siteInfo = []; var part_str = '[{"part":"00000PD","partSupplier":"DELL"}]'; var part = part_str.substring(1,part_str.length-1); eval('var partobj='+part ); console.log(par ...

Client-side image upload problem in Next.js API routes

I've been banging my head against this bug for a couple of hours now and I just can't seem to figure out the reason behind it. The issue is with an API route I'm trying to set up in next.js where I need to modify an image and then upload it ...

Transformation of Array of Objects to Array of Values using Node.js

I am looking to transform the following: [{ prop1: '100', prop2: false, prop3: null, prop4: 'abc' }, { prop1: '102', prop2: false, prop3: null, prop4: 'def' } ] into this format: [[100,false,null,'abc&ap ...

Evaluate One Input Value to Determine Another Input Value

Hey there, I've made an update to the fiddle but let me clarify what I'm trying to achieve. My goal is not to implement form validation as I already have that covered with the HTML5 "required" attribute. What I'm aiming for is to customize t ...

Validating minimum and maximum values with Angular 2 FormBuilder

I am currently developing a form using Angular 2 Formbuilder and I want to ensure that users can only input positive values into the amount field (with a minValue of 0 and maxValue of 100). How can I go about implementing minimum and maximum value validati ...

How can one locate a particular element/style/class in the dev tools DOM while debugging in MUI v5?

Exploring the DOM and pinpointing the specific component file and style block in MUI v4 is a straightforward process: Locating a particular element/style class in MUI v4 However, in MUI v5, this functionality is no longer available, making it challenging ...

Implementing non-blocking asynchronous object return in a node.js function

Struggling with a function that accesses data from a JSON file and queries it for a specific key. Unfortunately, the return function seems to be executing before the query can find the key. Even after querying and attempting to return the variable queryre ...

How can I track and log the name of the country each time it is selected by a click?

I'm currently utilizing VueJS along with a REST API and axios to retrieve the list of countries, then showcasing them in card format on the webpage. However, I am facing a challenge in creating a history list that captures the last 5 countries clicked ...

Transfer data from href link to specific detail page

I am currently working on a table that displays all the users. My goal is to turn the usernames into clickable links that direct you to their profile page. What steps should I take to convert the username into an href link and send it to the detail page? ...

"Encountering a problem with a missing object in jQuery when referencing

I'm encountering an issue with jQuery's $(this) object that's causing me to lose track of the this element in my code: $('.star').click(function (){ var id = $(this).parent().attr('id').split('rating')[ ...

Learn the proper way to write onClick in tsx with Vue 2.7.13

current version of vue is 2.7.13 Although it supports jsx, I encounter a type error when using onClick event handling. The type '(event: MouseEvent) => Promise<void>' cannot be assigned to type 'MouseEvent' Is there a correct ...

Preserving CSS styling while loading an HTML page with InnerHTML

By using the following code snippet, I have successfully implemented a feature on my website that allows me to load an HTML page into a specific div container when clicking a link in the menu. However, I encountered an issue where the background color of ...

Exploring JSON without taking into account letter case

Looking to conduct a case-insensitive search in a JSON file? Here's the JSON data you can work with: { "Data" : [ {"Name": "Widget", "Price": "25.00", "Quantity": "5" }, {"Name": "Thing", "Price": "15.00", "Quantity": "5" }, {"Nam ...

Adding data to an AngularJS template

I am encountering an issue with a flag that I am toggling between true and false to alter the display of certain elements on my page. While it works outside of the template, integrating this value into the template itself has proven challenging. restrict: ...

What is the best way to conceal text while retaining icons on a compact screen?

How can I hide the text links for Home, Reservations, My Reservations, About, and Settings on smaller screens while still keeping the icons visible? Currently, I am using the following resources: http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.1 ...

Having trouble with flash messages in Node.js?

Could anyone shed some light on why the flash messages are not displaying properly in my situation? Here is how I'm attempting to utilize them: This snippet is from my app.js file: var express = require('express'); var app = express ...

I'm encountering difficulties with customizing the root styling of material-ui's DialogActions

Check out the two buttons in a DialogActions just like this. This is the JSX snippet I'm working with: <DialogActions classes={{ root: classes.dialogActionsLeft }}> <Button autoFocus onClick={() => { setOpen(false); }} ...

Learn how to efficiently disable or enable a button in Angular depending on the selected radio button

In order to disable the button when the remarks are marked as failed. Here is an example scenario: Imagine there is an array containing two to four items. First example: ITEM 1 -> FAILED -> Remarks (required) ITEM 2 -> FAILED -> Remarks (r ...

The $postLink() method in the controller is encountering a null value for this.$scope

class pageController { constructor($scope, MyEditableGrid) { this.$scope = $scope; this.MyEditableGrid = MyEditableGrid; this.myEditableGrid = { appScope: this.$scope, ..... } } $postLink ...

Initiate the React application with the given external parameters

I have created a React app that is embedded within a webpage and needs to start with specific parameters obtained from the page. Currently, I am passing these parameters in the index.HTML file within a div element. The issue arises when these parameters ar ...