ochj1ch ochj1ch - 1 month ago 10
CSS Question

JS animation from zero to current amount

Everytime I click the button it add +10(counter) width.
I want the animation to go from width 0 to "counter" width everytime i click the button, but it always starts from last position.
I want the animation to go from 0px to "counter" px
Do you please know how to solve it? Thank you :)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
font-size: 50px;
}
#demo {
width: 100px;
height: 100px;
background-color: #f00;
transition: width 1s ease;
}

</style>
</head>
<body>
<div id="demo">
<br><br><br>
<button onclick="myFunction()">TRY</button>
</div>
</body>
<script type="text/javascript">
counter = 0;
function myFunction() {
document.getElementById("demo").style.width="0px";
counter+=10;
document.getElementById("demo").style.width=counter+"px";
}
</script>
</html>

Answer

Use setTimeout() with duration set to same as css transition, call document.getElementById("demo").style.width = counter + "px"; within setTimeout()

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    * {
      font-size: 50px;
    }
    #demo {
      width: 100px;
      height: 100px;
      background-color: #f00;
      transition: width 1s ease;
    }
  </style>
</head>

<body>
  <div id="demo">
    <br>
    <br>
    <br>
    <button onclick="myFunction()">TRY</button>
  </div>
</body>
<script type="text/javascript">
  counter = 0;

  function myFunction() {
    document.getElementById("demo").style.width = "0px";
    counter += 10;
    setTimeout(function() {
      document.getElementById("demo").style.width = counter + "px";
    }, 1000)
  }
</script>

</html>