How to create: JavaScript progress bar

Learn how to create a progress bar using JavaScript.

Create progress bar

Step 1 - Add HTML:

<div id="myProgress">
  <div id="myBar"></div>
</div>

Step 2 - Add CSS:

#myProgress {
  width: 100%;
  background-color: grey;
}
#myBar {
  width: 1%;
  height: 30px;
  background-color: green;
}

Step 3 - Add JavaScript:

Create a dynamic progress bar with JavaScript (animation effect):

var i = 0;
function move() {
  if (i == 0) {
    i = 1;
    var elem = document.getElementById("myBar");
    var width = 1;
    var id = setInterval(frame, 10);
    function frame() {
      if (width >= 100) {
        clearInterval(id);
        i = 0;
      } else {
        width++;
        elem.style.width = width + "%";
      }
    }
  }
}

Try it yourself

Add label

If you want to add a label to indicate the user's progress in the current process, you can add a new element inside (or outside) the progress bar:

Step 1 - Add HTML:

<div id="myProgress">
  <div id="myBar">10%</div>
</div>

Step 2 - Add CSS:

#myBar {
  width: 10%;
  height: 30px;
  background-color: #04AA6D;
  text-align: center; /* Center horizontally (if needed) */
  line-height: 30px; /* Center vertically */
  color: white;
}

Try it yourself

Step 3 - Add JavaScript:

If you want to dynamically update the text inside the label to match the width value of the progress bar, please add the following content:

var i = 0;
function move() {
  if (i == 0) {
    i = 1;
    var elem = document.getElementById("myBar");
    var width = 10;
    var id = setInterval(frame, 10);
    function frame() {
      if (width >= 100) {
        clearInterval(id);
        i = 0;
      } else {
        width++;
        elem.style.width = width + "%";
        elem.innerHTML = width + "%";
      }
    }
  }
}

Try it yourself