0

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

3 Answers 3

3

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer it worked perfectly! You were right, it didn't have to be a keyframe animation. I'm a beginner and that was the only way I knew how to animate something. Thanks again!
1

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

Comments

1

@JohnUleis already answeared correctly. I was too late. But I add just for fun a solution. Is named: How far 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>

2 Comments

All ways lead to Rome!
@four-eyes I see you know oder besser: Ick sehe du weßt bescheid ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.