Simple progress bar with CSS

Lengthy background operations should give the user some feedback of the progress. Typically applications show spinners and various animation as well as progress meters to keep the user updated while the process is ongoing. Making a progress bar is extremely simple and requires only one element on a webpage. In addition to this element some styling attributes are also needed to set up the functionality. With a little JavaScript code the progress bar becomes alive while the code constantly updates the screen. The following HTML element serves as the progress bar.

<div id="meter" style="background-color: red; height: 10px; width: 40%;></div>

This simple progress meter has style attribute with some basic values such as progress bar color and height. Varying these values you can easily style the element for your needs. Width of the element is important. I use percentage value to show the progress. If you are using popular jQuery library, you can update the element width by increasing and decreasing it according to the process phase. The following short JavaScript snippet does the trick.

$('#meter').css('width', '10%');

Now, changing the value in the css method the width of the div element changes displaying the progress. By substituting the constant value with a function you can get even more sophisticated application, like the one below.

$('#meter').css('width', function() {   // calculate new width   return parseInt(completed / total * 100).toString() + '%'; });

The code has variable total, which is the total value of the progress. Assume your operation has five steps, then the total would be 5. Similarly, variable completed indicates the current phase. For example, if the user has completed two steps out of five, then the value would be 2. These variables can contain any numeric values for unlimited number of applications. Making a quick and dirty progress bar is only a matter of minutes and with a little help of jQuery you can kiss goodbye to tedious JavaScript coding.

Julkaistu perjantaina 6.1.2012 klo 18:39 CSS-luokassa avainsanalla ohjelmointi.

Edellinen
Vilpittömästi
Seuraava
Sosiaalinen suihkuverho