JavaScript progress bar indicator

Need a way to show the progress on a long process on your web page? Here's a quick little JavaScript routine that will do it for you.

The trick is to create a fixed size div with the background image set to the progress bar. We're then going to overlay a right floating white image over the div to hide the part of the indicator that shouldn't be shown.

First we need to add a little bit of CSS.

CSS:
  1. /*  CSS for JavaScript status bar */
  2. .statusBar  {
  3.     background: url(statusIndicator.png) no-repeat;
  4.     width: 300px;
  5.     height: 15px;
  6.     border:1px solid silver;
  7.     }
  8. .whiteOverlay {
  9.     float:right;
  10.     height:15px;
  11.     }

And the JavaScript code.

JavaScript:
  1. function setPercentage(percentage)
  2.     {
  3.     /*  We're subtracting (percentage * 3) from 300 because the div
  4.         width is 300 pixels.  If it was 400 wide we'd do
  5.         400 - (percentage*4).   */
  6.     newWidth = 300 - (percentage * 3) + 'px';
  7.     document.getElementById('whiteOverlay').style.width = newWidth;
  8.     }

Notice the '300 - (percentage * 3)'. We're using 300 and 3 because the div is 300 pixels wide. If your background div is 400 pixels wide then you'd use '400 - (percentage * 4)'.

In the HTML we just need to create the div with the image in it and then call the JavaScript routine whenever we want to update the percentage.

HTML:
  1. <div id="statusIndicator" class="statusBar"><img class="whiteOverlay" id="whiteOverlay" src="white.gif"></div>
  2. <script type="text/javascript">
  3. setPercentage(70);
  4. </script>

The code above just sets the percentage to 70%, but if you want to change it through code just call setPercentage() whenever you want to update it.

Download
If you'd like to download the code, along with the supporting graphic files, just click the link below.
[download id=4]

Question, Comments...

Do you have more questions. Please either leave a comment below or join us in our new forum.

One Response to “JavaScript progress bar indicator”

  1. Nice! Could you please fix the missing link! Many thanks!

Leave a Reply