Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!