Friday, 6 January 2012

Progress Bar Using JavaScript

You can create a simple progress bar using JavaScript and HTML. It shows graphically the percentage of work completed along with numeric indication. A JavaScript function prog_bar is used here.


Syntax


prog_bar(cur_val,min_val,max_val,width,height,border,fill);


The function has seven parameters. They are described below.

cur_val : Represents current progress. It should be an Integer.
min_val : Represents value that corresponds to 0%. It should be an integer.
max_val : Represents value that corresponds to 100%. It should be an integer.
width : Width of the progress bar in pixels. It should be an integer.
height : Height of the progress bar in pixels. It should be an integer.
border : Represents the border color. It should be a string.
fill : Represents the fill color. It should be a string.


The progress bar will be created in a <div> element with id prog_bar. So make sure that a div element with id prog_bar is created in the body of html page where the progress bar should appear. Also make sure that the function call occurs only after the div element is created.


Example


prog_bar(87,0,100,200,5,"#0066FF","#99FFFF");


The above function call statement will produce the following result in the web page.








Code


The complete code (HTML page and JavaScript function) to implement the progress bar is given below. To run it, copy the entire code to a text editor and save it with file extension ".html". Then open it using any web browser.


<html>
<head>
<title>Progress Bar Using Javascript</title>
<script type="text/javascript">
function prog_bar(cur_val,min_val,max_val,width,height,border,fill)
{
var str = "",res = 0;
if(cur_val>=min_val && cur_val<=max_val)
{
  if(min_val<max_val)
  {
    res = ((cur_val-min_val)/(max_val-min_val))*100;
res = Math.floor(res);
  }
  else
  {
    res = 0;
  }
}
else
{
  res = 0;
}
str = str + "<div style=\"border:"+border+" solid thin; width:"+width+"px; height:"+height+"px;\">";
str = str + "<div style=\"background-color:"+fill+"; width:"+res+"%; height:"+height+"px;\">";
str = str + "</div></div>";
str = str + res + "%";
document.getElementById("prog_bar").innerHTML = str;
}
</script>
</head>


<body>
<div id="prog_bar">
</div>
<script type="text/javascript">
prog_bar(87,0,100,200,5,"#0066FF","#99FFFF");
</script>
</body>
</html>

1 comment:

  1. After examine a few of the weblog posts in your website now, and I truly like your approach of blogging. I bookmarked it to my bookmark web site listing and can be checking back soon. Pls take a look at my site as nicely and let me know what you think. online casinos

    ReplyDelete