▶ First, you need to add an HTML element that will show the progress:
<div id = "progress"></div>
▶ Then, you can use the following JavaScript code:
var
/* The elements */
bar = document.getElementsByClassName("bar")[0],
barFill = document.getElementsByClassName("bar-fill")[0],
progress = document.getElementById("progress"),
/* The bar's total width */
barWidth = window.getComputedStyle(bar, null).getPropertyValue("width"),
/* How much of the bar is filled */
barFillWidth = window.getComputedStyle(barFill, null).getPropertyValue("width"),
/* Create the percentage */
pct = 100 * (parseFloat(barFillWidth) / parseFloat(barWidth)) + "%";
/* Set the innerHTML of our progress element */
progress.innerHTML = pct;
Check out this fiddle or the following snippet for a visual representation.
Snippet:
(function() {
var
bar = getByClass("bar"),
barFill = getByClass("bar-fill"),
progress = document.getElementById("progress"),
barWidth = getWidth(bar),
barFillWidth = getWidth(barFill),
pct = 100 * barFillWidth / barWidth + "%";
progress.innerHTML = pct;
function getWidth(element) {
return parseFloat(window.getComputedStyle(element, null).getPropertyValue("width"));
};
function getByClass(className) {
return document.getElementsByClassName(className)[0];
}
})();
.container {
display: inline-block;
width: 300px;
}
.bar {
width: 100%;
background-color: #E3E3E3;
border-radius: 10px;
}
.bar-fill {
height: 15px;
display: block;
background: #0073CF;
width: 60%;
border-radius: 7.5px;
-webkit-transition: width 0.8s ease;
transition: width 0.8s ease;
}
#progress {
position: relative;
bottom: 3px;
display: inline-block;
}
<div class="container">
<div class="bar">
<span class="bar-fill"></span>
</div>
</div>
<div id="progress"></div>
To position the label next to the progressbar, there are a lot of things you can do. I'm mentioning two of them below:
- You can put
position: absolute to #progress to get it out of the normal flow, so that it can be 'inline' with .bar as the bar currently occupies 100% of the container's width.
- You can put
#progress outside of the container as a sibling and put display: inline-block to both of them.
currentProgress = 60. Based on that, you will make the progress bar take up 60% width, and you will also know to display the number "60" in the progress bar. Example: jsfiddle.net/h5xgfyrp/6