nbray
nbray

Reputation: 81

Using JavaScript variable in CSS

I have some JavaScript here:

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


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

I also 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 is essentially fading an image in and out every 7 seconds. I'd like that time unit to be variable, like var x in my JavaScript. How do I do that? I assume I can't just do:

<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>

Upvotes: 0

Views: 85

Answers (3)

OK sure
OK sure

Reputation: 2646

If you don't care too much about IE (at the time of writing), you could look into the new CSS Variables.

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

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

Otherwise, a CSS preprocessor like SASS or SCSS would let you set up such variables easily to be compiled to CSS.

Upvotes: 0

khalil et
khalil et

Reputation: 45

you can set the duration property using javascript and the rest of properties using css like this: 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}}

notice that got rid of the duration property in css code. hope that helps you.

Upvotes: 0

Chris Riebschlager
Chris Riebschlager

Reputation: 1333

You can't really set the variable IN the CSS, but you can apply the style directly to the element using JS:

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

Or if you want to apply it to every element with that class:

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

Upvotes: 1

Related Questions