Home > Enterprise >  Change keyframes values in Javascript
Change keyframes values in Javascript

Time:12-18

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%;
  }
}

CodePudding user response:

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

CodePudding user response:

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');

CodePudding user response:

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

  • Related