Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
Change keyframes values in Javascript

I have this piece of css but I want to change the width in the keyframe with a variable in javascript. How can I do that?

@keyframes test {
  100% {
    width: 100%;
  }
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Does it have to be a keyframe animation? Typically you would use the CSS transition property for this kind of animation powered by JavaScript, like this:

var width = 50;

document.getElementById('button').addEventListener('click', () => {
  width += 50;
  document.getElementById('box').style.width = `${width}px`;
});
#box {
  background: red;
  height: 50px;
  width: 50px;
  transition: width .5s;
  margin-bottom: 1em;
}
<div id="box"></div>

<button id="button">Change Width</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

If you have a more general animation (that can't be encompassed by just doing a transition) then you can use JS to set a CSS variable.

Taking the example in the question, replace the 100% with a variable:

@keyframes test {
  100% {
    width: var(--bg);
  }
}

and the Javascript you'd have something like:

thediv.style.setProperty('--bg', '60px');
about 4 years ago · Juan Pablo Isaza Relatório

0

@JohnUleis already answeared correctly. I was too late. But I add just for fun a solution. Is named: How lfar is Rom? ;-)

Cheers

let root = document.documentElement;
const div = document.querySelector('div');
root.addEventListener("mousemove", e => {
  div.style.setProperty('--width', e.clientX + "px");
  div.innerHTML = e.clientX + ' km';
});
:root {
  --width: 100%; 
}

div {
  background: hotpink;
  width: var(--width);
  text-align: center;
  color: white;
}
<div>how far is rom?</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda