Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda