Frontendplace Blog

Sharing Frontend developing ideas

Creating a progressbar with jQuery and CSS3

Posted by info on March 27th, 2011


For a client I had to create a progress bar to show the progress of several tasks. Here is an example I made to create the progress bar visually.

You can see it work here

First the html:

<p class="progress">
      <a  href="#" title="50% finished" >50%</a>
</p>

The rest is scripting and css:
In steps:

  1. get all the anchors inside the paragraphs with class =”progress”:

    $('.progress a')

  2. get the innerHTML and set the width of the anchor to the percentage you find:

    $('.progress a').attr("style", function () {
    	return "width:" + $(this).html();// same as this.innerHTML;
    });

See the example for the css. I used one background image, box-shadow and border-radius to make it fancy.

That is basically it. But you can off course make it fancier with colouring and animation like this:

$('.progress a').each(function(){
	// get percentage
	var innerText = $(this).html();
	$(this).attr("style", "width:0%");
	$(this).animate({width:innerText}, 'slow');
	// don't animate then use this $(this).attr("style", "width:"+innerText);
	var percentage = parseInt(innerText,10);
	if(percentage) {
		percentage = Math.round(percentage/25)*25;
			switch (percentage) {
				case 0: background = 'red'; break;
				case 25: background = 'orange'; break;
				case 50: background = 'yellow'; break;
				case 75: background = 'yellowgreen'; break;
				case 100: background = 'green'; break;
				default: background = 'red';
			}
		}
		else background = 'red';
		//var  rgb = "rgb(80%,"+(100 - percentage)+"%,"+(100- percentage)+"%)";
		var color = (percentage > 50 || percentage < 25)? "#FFF" : "#666";
		$(this).css("background-color", background);
		$(this).css("color", color);
	});