A Progress Bar is used to depict the progress of any task which is being carried out. Progress Bars are generally used to show the download and upload status. In other words we can say that, Progress Bars can be used to depict the status of anything that is in progress.
To create a basic Progress Bar using JavaScript, the following steps needs to be carried out:
1. Create HTML structure for your progress bar:
The code below contains two “div” tag elements named “Progress_Status” and “myprogressbar”.
<divid="Progress_Status"><divid="myprogressBar"></div></div>
2. Adding CSS:
The code below is used to set the width and the background color of the progress bar as well as the progress status in the bar.
#Progress_Status {
width: 50%;
background-color: #ddd;}
#myprogressBar {
width: 1%;
height: 35px;
background-color: #4CAF50;
text-align: center;
line-height: 32px;
color: black;}
3. Adding JavaScript:
The code below creates a dynamic progress bar(animated) using javascript functions “update” and “scene”.
function update() {
var element = document.getElementById("myprogressBar");
var width = 1;
var identity = setInterval(scene, 10);
function scene() {
if (width >= 100) {
clearInterval(identity);
} else {
width++;
element.style.width = width + '%';
}
}
}
4. Link the HTML,CSS and JavaScript elements
Below program shows the complete code of progress bar linking the above HTML, CSS and JavaScript Codes:
<!DOCTYPE html><html><style>#Progress_Status {width: 50%;background-color: #ddd;}#myprogressBar {width: 2%;height: 20px;background-color: #4CAF50;}</style><body><h3>Example of Progress Bar Using JavaScript</h3><p>Download Status of a File:</p><divid="Progress_Status"><divid="myprogressBar"></div></div><br><buttononclick="update()">Start Download</button><script>function update() {var element = document.getElementById("myprogressBar");var width = 1;var identity = setInterval(scene, 10);function scene() {if (width >= 100) {clearInterval(identity);} else {width++;element.style.width = width + '%';}}}</script></body></html>