Skip to content

Instantly share code, notes, and snippets.

@kparms
Created March 11, 2014 14:16
Show Gist options
  • Save kparms/9486604 to your computer and use it in GitHub Desktop.
Save kparms/9486604 to your computer and use it in GitHub Desktop.
JavaScript to draw a percentage bar in a <div>
Taken from here:
http://www.alpinemeadow.com/stitchery/weblog/HTML-morsels.html
function drawPercentBar(width, percent, color, background)
{
var barhtml = "";
var pixels = width * (percent / 100);
if (!background) { background = "none"; }
barhtml = "<div style=\"position: relative; line-height: 1em; background-color: "
+ background + "; border: 1px solid black; width: "
+ width + "px\">";
barhtml += "<div style=\"height: 1.5em; width: " + pixels + "px; background-color: "
+ color + ";\"></div>";
barhtml += "<div style=\"position: absolute; text-align: center; padding-top: .25em; width: "
+ width + "px; top: 0; left: 0\">" + percent + "%</div>";
barhtml += "</div>";
return barhtml;
}
How to call the function (will return html):
drawPercentBar(100, '35', 'red');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment