How to put javascript variable value in CSS?

Asked

Viewed 1,454 times

2

I have on the style page (css) of the site a code to make an animation, but the animation time should vary according to a variable that is in javascript, how do I make the value of this variable enter in my css code?

css

div.progresso {
    animation: loading "tempo"s ease;
}

javascript

<script >
    var som1 = document.getElementById("player");
    som1.onloadeddata = function() {
    console.log("tempo:" + player.duration + "segundos");;
    var tempo = player.duration;
    <codigo pra colocar o valor da 'var tempo' naquele lugar especifico do css>
</script>

How could I do that?

  • Try using the style property: document.querySelector("div.progresso").style.animation = "loading " + tempo + "s ease"

  • Po worked perfectly there yes ein partner. Thank you!

1 answer

4


You can use the CSS variables themselves and update via Javascript. Ex.:

Defining the variable via CSS.

:root{
    --tempo-animacao: 1s;
}

div.progresso {
    animation: loading var(--tempo-animacao) ease;
}

Updating by JS.

var root = document.documentElement;

var som1 = document.getElementById("player");
som1.onloadeddata = function() {
   console.log("tempo:" + player.duration + "segundos");;
   var tempo = player.duration;
   root.style.setProperty('--tempo-animacao', tempo);
}    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.