Leveraging JavaScript variables within CSS

Below is a snippet of my JavaScript code:

<script>
    function random(n) {
        return ((Math.floor(Math.random() * Math.floor(n)))+1);
    }

var x = random(5000)+2000;
</script>

In addition, I have some CSS:

<style>

.fadingVariable{animation:fading 7s infinite}@keyframes fading{0%{opacity:0}20%{opacity:1}50%{opacity:1}80%{opacity:1}100%{opacity:0}}

</style>

The CSS above fades an image in and out every 7 seconds. I want to make this time interval variable using the 'x' value from my JavaScript. How can I achieve this? Can I simply write it like this:

<style>

.fadingVariable{animation:fading 'x's infinite}@keyframes fading{0%{opacity:0}20%{opacity:1}50%{opacity:1}80%{opacity:1}100%{opacity:0}}

</style>

Answer №1

Setting a variable within the CSS itself may not be possible, but you can still add styles directly to an element using JavaScript:

document.getElementById('myEl').style.animation = 'fading ' + x + 's infinite');

If you'd like to apply this style to multiple elements with the same class:

document.getElementsByClassName('fadingVariable').forEach(el => {
    el.style.animation = 'fading ' + x + 's infinite';
});

Answer №2

To adjust the duration of an animation using JavaScript and other properties using CSS, you can follow this method: JavaScript code :

var x = 7;
document.getElementById('fadingVariable').style.animationDuration = x + 's';

CSS code :

.fadingVariable{animation:fading infinite}@keyframes fading{0%{opacity:0}20%{opacity:1}50%{opacity:1}80%{opacity:1}100%{opacity:0}}

It's worth noting that the duration property has been removed from the CSS code. I hope this explanation helps!

Answer №3

If you're not too concerned about compatibility with IE (as of now), you might want to explore the latest CSS Variables.

:root {
    --fade-interval: 8s;
}

.fadingVariable {
    animation: fading var(--fade-interval) infinite
}
@keyframes fading {
    0% { opacity: 0 }
    20% { opacity: 1 }
    50% { opacity: 1 }
    80% { opacity: 1 }
    100% { opacity: 0 }
}

Alternatively, using a CSS preprocessor like SASS or SCSS would make it easy for you to define and compile such variables into CSS.

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

Setting a port in Next.js: A step-by-step guide

I have one application currently running on port 3000 and I need to run another application on a different port in React Next.js. How can I make this change? In my package.json file, the current scripts section looks like this: "scripts": { & ...

Managing AJAX Errors in PHPAJAX error handling tips for developers

My current code is only set up to display a general error message when an error occurs during execution. I want to improve it by returning specific error messages for different scenarios. However, I have not been able to find satisfactory solutions in my s ...

Sharing information between controllers while being initiated using $rootScope.$emit

I've created a common module that includes a controller, component, and template to initialize the app and set up the base layout. Within this module, there is also a stateful component that makes an HTTP GET request during initialization to fetch a b ...

Validating passwords using Vuetify

I am implementing password validation on my form using Vuetify validation rules: passwordRules: [ v => (v && v.length >= 1 && v.length <= 10) || 'Password length should be between 1 and 10', v => (v && v.l ...

Tips for showcasing a blurry image in NextJS while it's in the process of being fetched?

Is there a way to achieve a similar effect like the one showcased below? https://i.sstatic.net/9unuN.gif I've managed to do something similar with Gatsby, but I'm curious if it's achievable with NextJS as well. ...

Encountering a Parse Error problem on my live website

There seems to be a problem with my running website as it is blocked by an error that I am unable to identify. The error message reads: Parse error: syntax error, unexpected '[' in /home/content/62/11926462/html/wp-includes/pomo/mo.php on line 11 ...

Saving the selections from two drop-down menus into a single variable

I have a requirement to store the user selected values from two dropdown menus. These dropdowns are created using the selectize library in HTML: <div style="max-width: 200px"> <select id="dropdown-1" ...

Should I publish on a model that can be accessed as a list?

Hey there, everyone. I'm new to .net mvc and I have a listing page for students. The challenge I am facing is that I need to enter grades for all the students on the page at once, but the model is structured as a list which makes it difficult to save ...

Unable to interact with the <svg></svg> element and enter the desired value

The <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">...</svg> cannot be clicked and the value of <input class="opacity-0 absolute top-0 lef ...

Is it possible to send multiple buttons without specifying the exact quantity in Discord.js v13?

I am facing a challenge with sending buttons from an array. I have tested the code below, but it sends two different messages with buttons: array.flatMap(user => { const cs = new client.discord.MessageActionRow() .add ...

Guide on transforming a NaN value to 0 within an app.post function in a .js file

When I try to convert the value of question1 from NaN to 0 using parseInt in the code below, it doesn't seem to work. How can I properly convert it? app.post('/auth/total',function(req,res){ console.log(req.body); const { question1, ...

Error message in MS Edge API: 'browser has not been defined'

I'm currently in the process of developing an extension for the new Microsoft Edge browser. Upon loading the unpacked extension, I encountered the following error: Uncaught ReferenceError: browser is not defined According to the Microsoft Edge docu ...

Creating translucent artwork using textured canvases in THREE.js

In my THREE.js application, I am creating 2D surfaces using PlaneGeometry and BasicMaterial meshes, while also supporting textures with a canvas: this.canvas = makeCanvas(canvasWidth, canvasHeight); this.ctx = this.canvas.getContext('2d'); this ...

Error encountered: `npm ERR! code E503`

While attempting to execute npm install on my project, which was cloned from my GitHub repository, I encountered the following error: npm ERR! code E503 npm ERR! 503 Maximum threads for service reached: fs-extra@https://registry.npmjs.org/fs-extra/-/fs-ex ...

Having trouble mapping my JSON to a Spring Boot @RequestBody POJO

I'm struggling with an issue where I have a hard-coded JSON object that is supposed to map to my POJO in Spring Controller, but I keep getting null values. I have double-checked my getters and setters, and everything seems to be correct. Can anyone he ...

Having trouble retrieving Bengali-language data from the server using jQuery AJAX

I am facing an issue where I am unable to fetch data in Bengali language from the server using ajax. Strangely, the data retrieved from the server is getting replaced by some unknown characters. However, if I directly retrieve the data without using ajax, ...

What is the best way to preserve the scroll location when revisiting a page with lazy loading enabled?

My question is quite straightforward, just like the title suggests. I am looking to implement a feature similar to Twitter's behavior where when users navigate away from a page and return using the browser's back button, they are taken back to wh ...

Warning: The React Router v6's Route component is unable to find the origin of the key props

I recently came across an error in my console and I'm unsure which list is causing it. Is there a way for me to trace back the origin of this error so I can pinpoint where to fix it? The error seems to be related to the React Router component, which ...

Achieving the Date format in electron with JavaScript

Is there a way to determine the date format currently being used on the device? For example, if I call a specific function, could it provide me with the current format? var dateFormat = getDateFormat(); console.log(dateFormat); MM/dd/YYYY Does anyone hav ...

Ways to transfer information from the Component to the parent in AngularJS 1.x

I am facing an issue with my component that consists of two tabs containing input fields. I need to retrieve the values from these input fields when the SAVE button is clicked and save them to the server. The problem lies in the fact that the SAVE function ...