THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

How TO - JavaScript Progress Bar


Learn how to create a progress bar using JavaScript.



Creating a Progress Bar

Step 1) Add HTML:

Example

<div id="myProgress">
    <div id="myBar"></div>
</div>
Step 2) Add CSS:

To make an animation possible, the animated element must be animated relative to its "parent container".

Example

#myProgress {
    position: relative;
    width: 100%;
    height: 30px;
    background-color: grey;
}
#myBar {
    position: absolute;
    width: 1%;
    height: 100%;
    background-color: green;
}
Try it yourself »
Step 3) Add JavaScript:

Create the Animation Using JavaScript:

Example

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

Add Labels

If you want to add labels to indicate how far the user is in the process, add a new element inside (or outside) the progress bar:

Step 1) Add HTML:

Example

<div id="myProgress">
  <div id="myBar">
    <div id="label">10%</div>
  </div>
</div>
Step 2) Add CSS:

Example

/* If you want the label inside the progress bar */
#label {
    text-align: center; /* If you want to center it */
    line-height: 30px; /* Set the line-height to the same as the height of the progress bar container, to center it vertically */
    color: white;
}
Try it yourself »
Step 3) Add JavaScript:

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

Example

function move() {
    var elem = document.getElementById("myBar");
    var width = 10;
    var id = setInterval(frame, 10);
    function frame() {
        if (width >= 100) {
            clearInterval(id);
        } else {
            width++;
            elem.style.width = width + '%';
            document.getElementById("label").innerHTML = width * 1 + '%';
        }
    }
}
Try it yourself »