I am trying to implement a CSS transition where I need to reset the width of my box in advance every time my function is called. Simply setting the width of the box to zero makes the element shrink with animation, but I want to reset it without any animation. To achieve this, I created a class that disables and enables the effect before and after resetting the width. However, this approach is not working as expected. It seems like JavaScript is asynchronous and skips over the width=0 command quickly. I discovered that inserting an alert before removing the "notransition" class fixes the issue, but this is not a proper solution.
I have been looking for a resolution to this async problem. Any explanation and solution regarding my attempt would be greatly appreciated, along with possibly a better method for resetting the width. Thank you!
function test() {
var duration = 5;
document.getElementById("box").classList.add('notransition');
document.getElementById("box").style.width = 0 + "%"
document.getElementById("box").classList.remove('notransition');
//Fill progress bar
document.getElementById("box").style.setProperty('transition-duration', duration + 's');
document.getElementById("box").style.width = 100 + "%"
setTimeout(function () {
console.log("Progress finished")
}, duration * 1000);
}
* {
box-sizing: border-box;
}
html {
padding: 0;
margin: 0;
width: 100%;
}
body {
margin: 0;
width: 100%;
padding: 20px;
}
#box {
border: 1px solid red;
height: 20px;
width: 10%;
background-color: rgba(219, 72, 72, 0.3);
transition-property: width;
transition-duration: 0s;
transition-timing-function: linear;
}
.notransition {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
transition: none !important;
}
<div id="box" onclick="test()"></div>