[javascript] How to make a progress bar

How would one go about making a progress bar in html/css/javascript. I don't really want to use Flash. Something along the lines of what can be found here: http://dustincurtis.com/about.html

All I really want is a 'progress bar' that changes to the values I give in PHP. What would be your though process? Are there any good tutorials on this?

This question is related to javascript html css progress-bar

The answer is


You can create a progress-bar of any html element that you can set a gradient to. (Pretty cool!) In the sample below, the background of an HTML element is updated with a linear gradient with JavaScript:

myElement.style.background = "linear-gradient(to right, #57c2c1 " + percentage + "%, #4a4a52 " + percentage + "%)";

PS I have set both locations percentage the same to create a hard line. Play with the design, you can even add a border to get that classic progress-bar look :)

enter image description here

https://jsfiddle.net/uoL8j147/1/


_x000D_
_x000D_
<html>_x000D_
<style>_x000D_
#myProgress {_x000D_
  width: 100%;_x000D_
  background-color: #ddd;_x000D_
}_x000D_
_x000D_
#myBar {_x000D_
  width: 10%;_x000D_
  height: 15px;_x000D_
  background-color: #4CAF50;_x000D_
  text-align: center;_x000D_
  line-height: 15px;_x000D_
  color: white;_x000D_
}_x000D_
</style>_x000D_
<body onload="move()">_x000D_
_x000D_
<div id="myProgress">_x000D_
  <div id="myBar">10%</div>_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
var i = 0;_x000D_
function move() {_x000D_
  if (i == 0) {_x000D_
    i = 1;_x000D_
    var elem = document.getElementById("myBar");_x000D_
    var width = 10;_x000D_
    var id = setInterval(frame, 10);_x000D_
    function frame() {_x000D_
      if (width >= 100) {_x000D_
        clearInterval(id);_x000D_
        i = 0;_x000D_
      } else {_x000D_
        width++;_x000D_
        elem.style.width = width + "%";_x000D_
        elem.innerHTML = width  + "%";_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_


Though one can build a progress bar using setInterval and animating its width

For best performance while animating a progress bar one has to take into account compositor only properties and manage layer count.

Here is an example:

_x000D_
_x000D_
function update(e){_x000D_
  var left = e.currentTarget.offsetLeft;_x000D_
  var width = e.currentTarget.offsetWidth_x000D_
  var position = Math.floor((e.pageX - left) / width * 100) + 1;_x000D_
  var bar = e.currentTarget.querySelector(".progress-bar__bar");_x000D_
  bar.style.transform = 'translateX(' + position + '%)';_x000D_
}
_x000D_
body {_x000D_
  padding: 2em;_x000D_
}_x000D_
_x000D_
.progress-bar {_x000D_
  cursor: pointer;_x000D_
  margin-bottom: 10px;_x000D_
  user-select: none;_x000D_
}_x000D_
_x000D_
.progress-bar {_x000D_
  background-color: #669900;_x000D_
  border-radius: 4px;_x000D_
  box-shadow: inset 0 0.5em 0.5em rgba(0, 0, 0, 0.05);_x000D_
  height: 20px;_x000D_
  margin: 10px;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  transform: translateZ(0);_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.progress-bar__bar {_x000D_
  background-color: #ececec;_x000D_
  box-shadow: inset 0 0.5em 0.5em rgba(0, 0, 0, 0.05);_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  transition: all 500ms ease-out;_x000D_
}
_x000D_
Click on progress bar to update value_x000D_
_x000D_
<div class="progress-bar" onclick="update(event)">_x000D_
  <div class="progress-bar__bar"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


You could use ProgressBar.js. No dependencies, easy API and supports major browsers.

var line = new ProgressBar.Line('#container');
line.animate(1);

See more examples of usage in the demo page.


Basically its this: You have three files: Your long running PHP script, a progress bar controlled by Javascript (@SapphireSun gives an option), and a progress script. The hard part is the Progress Script; your long script must be able to report its progress without direct communication to your progress script. This can be in the form of session id's mapped to progress meters, a database, or check of whats not finished.

The process is simple:

  1. Execute your script and zero out progress bar
  2. Using AJAX, query your progress script
  3. Progress script must somehow check on progress
  4. Change the progress bar to reflect the value
  5. Clean up when finished

If you need to show and hide progress bar inside your php and java script, then follow this step.Its a complete solution, no need of any library etc.

           //Design Progress Bar

  <style>
#spinner
{     
position: absolute;
left: 50%;
top: 50%;
background-color: white;
z-index: 100;

height: 200px;


width: 300px;
margin-left: -300px;

    /*Change your loading image here*/
   background: url(images/loading12.gif) 50% 50% no-repeat ;

}
  </style>

               //Progress Bar inside your Page

<div id="spinner" style=" display:none; ">
</div>                                

    // Button to show and Hide Progress Bar
<input class="submit" onClick="Show()" type="button" value="Show" /> 
<input class="submit" onClick="Hide()" type="button" value="Hide" /> 

            //Java Script Function to Handle Button Event     
<script language="javascript" type="text/javascript">
 function Show()
 {       
  document.getElementById("spinner").style.display = 'inline';
 }
function Hide()
 {       
  document.getElementById("spinner").style.display = 'none';
 }

</script>

Image link: Download image from here


http://jqueryui.com/demos/progressbar/

Check that out, it might be what you need.


var myPer = 35;
$("#progressbar")
    .progressbar({ value: myPer })
    .children('.ui-progressbar-value')
    .html(myPer.toPrecision(3) + '%')
    .css("display", "block");

You can use setInterval to create a progress bar.

_x000D_
_x000D_
function animate() {_x000D_
  var elem = document.getElementById("bar");   _x000D_
  var width = 1;_x000D_
  var id = setInterval(frame, 10);_x000D_
  function frame() {_x000D_
    if (width >= 100) {_x000D_
      clearInterval(id);_x000D_
    } else {_x000D_
      width++; _x000D_
      elem.style.width = width + '%'; _x000D_
    }_x000D_
  }_x000D_
}
_x000D_
#progress-bar-wrapper {_x000D_
  width: 100%;_x000D_
  background-color: #ddd;_x000D_
}_x000D_
_x000D_
#bar {_x000D_
  width: 1%;_x000D_
  height: 30px;_x000D_
  background-color: orange;_x000D_
}
_x000D_
<div id="progress-bar-wrapper">_x000D_
  <div id="bar"></div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<button onclick="animate()">Click Me</button>
_x000D_
_x000D_
_x000D_


I know the following doesn't work currently because browsers do not support it yet, but maybe some day this will help:

At the time of this post attr() on other properties than content is just a Candidate Recommendation1. As soon as it is implemented, one could create a progress bar with just one element (like the HTML 5 <progress/>, but with better styling options and text inside)

<div class="bar" data-value="60"></div>

and pure CSS

.bar {
    position: relative;
    width: 250px;
    height: 50px;
    text-align: center;
    line-height: 50px;
    background: #003458;
    color: white;
}

.bar:before {
    position: absolute;
    display: block;
    top: 0;
    left: 0;
    bottom: 0;
    width: attr(data-value %, 0); /* currently not supported */
    content: '';
    background: rgba(255, 255, 255, 0.3);
}

.bar:after {
    content: attr(data-value) "%";
}

Here is the currently not working demo.


1 Cannot imagine why this isn't implemented in any browser. First I'd think that if you have the functionality for content already, it should not be too hard to extend that (but of course I don't really know to be honest). Second: The above is just one good example showing how powerful this functionality could be. Hopefully they start to support it soon, or it won't even be part of the final specification.


I was writing up an answer to a similar question that got deleted, so I'm posting it here in case it's of use to anyone.

The markup can be dropped in anywhere and takes up 50px of vertical real estate even when hidden. (To have it take up no vertical space and instead overlay the top 50px, we can just give the progressContainerDiv absolute positioning (inside any positioned element) and style the display property instead of the visible property.)

The general structure is based on code presented in this Geeks for Geeks article.

_x000D_
_x000D_
const_x000D_
  progressContainerDiv = document.getElementById("progressContainerDiv");_x000D_
  progressShownDiv = document.getElementById("progressShownDiv");_x000D_
let_x000D_
  progress = 0,_x000D_
  percentageIncrease = 10;_x000D_
_x000D_
function animateProgress(){_x000D_
  progressContainerDiv.style.visibility = "visible";_x000D_
  const repeater = setInterval(increaseRepeatedly, 100);_x000D_
  function increaseRepeatedly(){_x000D_
    if(progress >= 100){_x000D_
      clearInterval(repeater);_x000D_
      progressContainerDiv.style.visibility = "hidden";_x000D_
      progressNumberSpan.innerHTML = "";_x000D_
      progress = 1;_x000D_
    }_x000D_
    else{_x000D_
      progress = Math.min(100, progress + percentageIncrease);_x000D_
      progressShownDiv.style.width = progress + "%";_x000D_
      progressNumberSpan.innerHTML = progress + "%";_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
#progressContainerDiv{_x000D_
  visibility: hidden;_x000D_
  height: 40px;_x000D_
  margin: 5px;_x000D_
}_x000D_
_x000D_
#progressBackgroundDiv {_x000D_
  width: 50%;_x000D_
  margin-left: 24%;_x000D_
  background-color: #ddd;_x000D_
}_x000D_
  _x000D_
#progressShownDiv {_x000D_
  width: 1%;_x000D_
  height: 20px;_x000D_
  background-color: #4CAF50;_x000D_
}_x000D_
_x000D_
#progressNumberSpan{_x000D_
  margin: 0 auto;_x000D_
}
_x000D_
<div id="progressContainerDiv">_x000D_
  <div id="progressBackgroundDiv">_x000D_
    <div id="progressShownDiv"></div>_x000D_
  </div>_x000D_
  <div id="progressNumberContainerDiv">_x000D_
    <span id="progressNumberSpan"></span>_x000D_
  </div>_x000D_
</div>_x000D_
<button type="button" onclick="animateProgress()">Go</button>_x000D_
<div id="display"></div>
_x000D_
_x000D_
_x000D_


Here is my approach, i've tried to keep it slim:

HTML:

<div class="noload">
    <span class="loadtext" id="loadspan">50%</span>
    <div class="load" id="loaddiv">
    </div>
</div>

CSS:

.load{    
    width: 50%;
    height: 12px;
    background: url( data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAALCAYAAAC+jufvAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwAAADsABataJCQAAABp0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuMTAw9HKhAAAAPklEQVQYV2M48Gvvf4ZDv/b9Z9j7Fcha827Df4alr1b9Z1j4YsV/BuML3v8ZTC/7/GcwuwokrG4DCceH/v8Bs2Ef1StO/o0AAAAASUVORK5CYII=);  
    -moz-border-radius: 4px;
    border-radius: 4px;
}

.noload{
    width: 100px;    
    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAALCAYAAAC+jufvAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwAAADsABataJCQAAABp0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuMTAw9HKhAAAANUlEQVQYVy3EIQ4AQQgEwfn/zwghCMwGh8Tj+8yVKN0d2l00M6i70XsPmdmfu6OIQJmJqooPOu8mqi//WKcAAAAASUVORK5CYII=);     
    -moz-border-radius: 4px;
    border-radius: 4px;
    border: 1px solid #999999;    
    position: relative;
}

.loadtext {
    font-family: Consolas;    
    font-size: 11px;
    color: #000000;
    position: absolute;
    bottom: -1px;
}

Fiddle: here

enter image description here


Infinitive progress bar using pure Javascript

<div id="container" style="width:100%; height:5px; border:1px solid black;">
  <div id="progress-bar" style="width:10%;background-color: green; height:5px;"></div>
</div>

<script>
  var width = 0;
  window.onload = function(e){ 
    setInterval(function () {
        width = width >= 100 ? 0 : width+5;  
        document.getElementById('progress-bar').style.width = width + '%'; }, 200);            
  }
</script>

Example http://fiddle.jshell.net/1kmum4du/


You could recreate the progress bar using CSS3 animations to give it a better look.

JSFiddle Demo

HTML

<div class="outer_div">
    <div class="inner_div">
        <div id="percent_count">

    </div>
</div>

CSS/CSS3

.outer_div {
    width: 250px;
    height: 25px;
    background-color: #CCC;
}

.inner_div {
    width: 5px;
    height: 21px;
    position: relative; top: 2px; left: 5px;
    background-color: #81DB92;
    box-shadow: inset 0px 0px 20px #6CC47D;
    -webkit-animation-name: progressBar;
    -webkit-animation-duration: 3s;
    -webkit-animation-fill-mode: forwards;
}

#percent_count {
    font: normal 1em calibri;
    position: relative;
    left: 10px;
}

@-webkit-keyframes progressBar {
    from {
        width: 5px;
    }
    to {
        width: 200px;
    }
}

I tried a simple progress bar. It is not clickable just displays the actual percentage. There's a good explication and code here: http://ruwix.com/simple-javascript-html-css-slider-progress-bar/


You can use progressbar.js; Animated progress bar control and tiny chart (sparkline)

Demo and download link

enter image description here

HTML usage;

<div id="my-progressbar"></div>

Javascript usage;

var progressBar;

window.onload = function(){

    progressBar = new ProgressBar("my-progressbar", {'width':'100%', 'height':'3px'});
    progressBar.setPercent(60);

}

I used this progress bar. For more information on this you can go through this link i.e customization, coding etc.

<script type="text/javascript">

var myProgressBar = null
var timerId = null

function loadProgressBar(){
myProgressBar = new ProgressBar("my_progress_bar_1",{
    borderRadius: 10,
    width: 300,
    height: 20,
    maxValue: 100,
    labelText: "Loaded in {value,0} %",
    orientation: ProgressBar.Orientation.Horizontal,
    direction: ProgressBar.Direction.LeftToRight,
    animationStyle: ProgressBar.AnimationStyle.LeftToRight1,
    animationSpeed: 1.5,
    imageUrl: 'images/v_fg12.png',
    backgroundUrl: 'images/h_bg2.png',
    markerUrl: 'images/marker2.png'
});

timerId = window.setInterval(function() {
    if (myProgressBar.value >= myProgressBar.maxValue)
        myProgressBar.setValue(0);
    else
        myProgressBar.setValue(myProgressBar.value+1);

},
100);
}

loadProgressBar();
</script>

Hope this may be helpful to somenone.


If you are using HTML5 its better to make use of <progress> tag which was newly introduced.

<progress value="22" max="100"></progress>

Or create a progress bar of your own.

Example written in sencha

if (!this.popup) {
            this.popup = new Ext.Panel({
            floating: true,
            modal: false,
            // centered:true,
            style:'background:black;opacity:0.6;margin-top:330px;',
            width: '100%',
            height: '20%',
            styleHtmlContent: true,
            html: '<p align="center" style="color:#FFFFFF;font-size:12px">Downloading Data<hr noshade="noshade"size="7" style="color:#FFFFFF"></p>',

            });
}
this.popup.show('pop');

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to progress-bar

How to Create a circular progressbar in Android which rotates on it? Dynamically change bootstrap progress bar value when checkboxes checked Tkinter: How to use threads to preventing main event loop from "freezing" File upload progress bar with jQuery CSS Progress Circle How to set the Android progressbar's height? How to use WinForms progress bar? Display a loading bar before the entire page is loaded Progress Bar with HTML and CSS How to change color in circular progress bar?