Saturday, May 8, 2010

Loading Bar with JavaScript

Add divs code to your page body, or wherever you want
<div id="div1"> <div
id="Div2" style="border: solid 1px #000000; width: 7px; height: 7px; background-color:
#D3D3D3; float: left; margin-right: 5px; margin-left: 5px;">
<
/div>
<div id="Div3"
style="border: solid 1px #000000; width: 7px; height: 7px; background-color: #D3D3D3;
margin-right: 5px; float: left;"> </div> <div
id="Div4" style="border: solid 1px #000000; width: 7px; height: 7px; background-color:
#D3D3D3; margin-right: 5px; float: left;"> </div>
<
div id="Div5" style="border:
solid 1px #000000; width: 7px; height: 7px; background-color: #D3D3D3; margin-right:
5px; float: left;"><
/div
> <div id="Div6" style="border: solid 1px #000000;
width: 7px; height: 7px; background-color: #D3D3D3; margin-right: 5px; float: left;">< /div>
<div id="Div7"
style="border: solid 1px #000000; width: 7px; height: 7px; background-color: #D3D3D3;
margin-right: 5px; float: left;"> </div
> <div id="Div8" style="border: solid 1px #000000;
width: 7px; height: 7px; background-color: #D3D3D3; margin-right: 5px; float: left;">
</div> </div>

Add these two buttons at the buttom of your progress bar (divs)
<input type ="button" id="btn_StartLoad" value ="Stop Loading" onclick ="StartLoading();" />

<input type="button" id="btn_StopLoad" value="Stop Loading" onclick="StopLoading();" />


Add these javascript functions to the same page which including divs and the two buttons.
var index = 1;
var prevIndex = 0;
var divCount = 7;
var loaded = false;
var Loading;

function StartLoading() {
    if (!loaded)
   {
      Loading = setInterval(DoLoading, 450);
   }
}

function DoLoading() {
  loaded = true;
  if (index > 1 && index != prevIndex) {
    prevIndex = index - 1;
    document.getElementById("loading"
+ prevIndex).style.backgroundColor = "#D3D3D3";
    document.getElementById("loading"
+ prevIndex).style.border = "solid 1px #000000";
  }
  else if (index > 1 && index == prevIndex)
{
    document.getElementById("loading"
+ (prevIndex - 1)).style.backgroundColor = "#000000";
    document.getElementById("loading"
+ (prevIndex - 1)).style.border = "solid 1px red";
    index = 1;
  }
  if (index <= divCount) {     document.getElementById("loading"
+ index).style.backgroundColor = "#000000";
    document.getElementById("loading"
+ index).style.border = "solid 1px red";
  if ((prevIndex - 1) == divCount) {
    document.getElementById("loading"
+ (prevIndex - 1)).style.backgroundColor = "#D3D3D3";
    document.getElementById("loading"
+ (prevIndex - 1)).style.border = "solid 1px #000000";
  }
  index++;
  if (index > divCount) {
    prevIndex = index;
  }
}
}

function StopLoading() {
  clearInterval(Loading);
  for (i = 1; i <= divCount; i++) {     document.getElementById("loading"
+ (i)).style.backgroundColor = "#D3D3D3";
    document.getElementById("loading"
+ (i)).style.border = "solid 1px #000000";
  }
  loaded = false;
  index = 1;
  prevIndex = 0;
  }

Example: