How to Create a Smooth Animated Progress Bar

jquery logo.png

While working on a timer component I needed a smooth animated progress bar so came up with the following. It only has a few lines of code and can be adapted to suit your own needs quite easily.

Here is an example. Click on the Start button:

STEP 1

First we will create a basic HTML5 template with links to our external stylesheet and jQuery:

STEP 2

The progress bar is made up of 2 divs:

  • an outer container div

  • an inner div which will be the animated bar

STEP 3

Now let's add some styling to the divs.

Hopefully the code should be fairly self-explanatory.

I have added rounded corners to the outer div and hence also added the overflow hidden rule so that the inner bar does not extend beyond the outer div.

STEP 4

We can now take care of the code to animate the inner bar.

Line 9: this ensures the code only runs once the page has rendered.

Line 10: we target the class of .innerBar and animate to a width of 100% over 5 seconds (5000 milliseconds).

STEP 5

At the moment the bar will begin animating once the page has loaded. 

However, I want it to start when a button has been clicked.

First we will add the code for the button (line 15):

STEP 6

Line 10: we target the id of the button (#start) and run a function when it has been clicked.

That's it!

You could add some styling to the button or even include Bootstrap on the progress bar and button.