I would like a bar to animate from left to right. I have a numerical input. After the submit click, the bar should then be animated.
Unfortunately, I don't know how to trigger the animation. I deliberately set the initial width value to 150px to show that the animation actually works, but it not works if be triggered programmatically.
btn = document.getElementById("btn");
btn.addEventListener('click', () => {
const val = document.querySelector('input').value
draw(val);
})
function draw(val) {
bar = document.getElementById("bar");
bar.style.setProperty('--width', (val * 10) "px");
}
:root {
--width: 150px;
}
#bar{
background:red;
height:50px;
margin:50px;
transform-origin:top;
animation: grow 2s forwards;
}
@keyframes grow {
from {
width:0px;
}
to {
width:var(--width);
}
}
<input value="5">
<button id="btn">draw</button>
<div id="bar"></div>
CodePudding user response:
Instead of animation, use CSS transtion
. Then (almost) any change to an element would be animated.
const runIt = () => {
$('.bar').css('width', '100%');
};
.bar {
height: 5px;
border-radius: 5px;
background: blue;
transition: 2s;
width: 10px;
margin-bottom: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>
<button onclick="runIt()">Run</button>
CodePudding user response:
This seems like a perfect use for CSS Transitions. Rather than adding an animation to the element, just set its width to have a transition
time. Then, any time you change the width, it will be animated.
const btn = document.getElementById("btn");
btn.addEventListener('click', () => {
const val = document.querySelector('input').value
draw(val);
})
function draw(val) {
bar = document.getElementById("bar");
bar.style.setProperty('width', (val * 10) "px");
}
#bar{
background:red;
width: 0;
height:50px;
margin:50px;
transform-origin:top;
transition: width 2s; /* Any time the width changes, it will be animated of 2 seconds */
}
<input value="5">
<button id="btn">Click Me</button>
<div id="bar"></div>