Khapi
Khapi

Reputation: 650

My HTML, CSS and JS progress bar doesn't work

I'm trying to do a progress bar so that the users can know when will their file be downloaded. I don't know what I did wrong, but the progress bar style doesn't update in the for loop.

var filesize = 1000 //this is not the final value 
var progressbar = document.getElementById("progress");
function myFunction(){
  for(var i = 0; i <= filesize; i++){
    x = i/ filesize * 100;
    x = parseInt(x.toString().slice(0, 3));
    console.log(x + "%")
    progressbar.style.width = x + "%";
  }
}
#bar{
    width: 35%;
    background-color: rgba(0,0,0,0.17);
    border-radius: 130px;
    margin: auto;
  }
  #progress{
    width: 0%;
    height: 30px;
    background-color: rgb(255, 0, 0);
    border-radius: 130px;
  }
    <button onclick="myFunction()">Click me</button>
    <div id="bar">
      <div id="progress"></div>
    </div>

Upvotes: 1

Views: 473

Answers (1)

Daemon Beast
Daemon Beast

Reputation: 2909

You can make the progress bar move smoothly by adding the transition property in CSS.

A higher transition time will result in the progress bar moving slower.

var filesize = 1000 //this is not the final value 
var progressbar = document.getElementById("progress");
function myFunction() {
  for (var i = 0; i <= filesize; i++) {
    x = i/ filesize * 100;
    x = parseInt(x.toString().slice(0, 3));
    console.log(x + "%")
    progressbar.style.width = x + "%";
  }
}
#bar {
  width: 35%;
  background-color: rgba(0,0,0,0.17);
  border-radius: 130px;
  margin: auto;
}
   
#progress {
  width: 0%;
  height: 30px;
  background-color: rgb(255, 0, 0);
  border-radius: 130px;
  transition: 0.2s;
}
<button onclick="myFunction()">Click me</button>
  <div id="bar">
    <div id="progress">
  </div>
</div>

Upvotes: 1

Related Questions