Interview Questions

Java Script Progress Bar

The following code is used to generate a progress bar in a JSP or HTML page using JavaScript.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sample Progress Bar</title>

<script language="javascript">
var statusCnt=1;
function updateProgressBar()
{
        document.getElementById('td'+statusCnt).style.background='green';
        if(statusCnt==25)
        {
                document.getElementById('percentage').innerHTML="Success... "+(statusCnt*4)+" %";
        }
        else
        {
                document.getElementById('percentage').innerHTML="Loading.... "+(statusCnt*4)+" %";
        }
    statusCnt=statusCnt+1;
   
    if(statusCnt<=25)
   {
                setTimeout("updateProgressBar()", 500);
   }
}

function init()
{
        updateProgressBar();
}

function callOnLoad(init)
{
   if (window.addEventListener)
   {
        window.addEventListener("load", init, false);
        }
        else if (window.attachEvent)
        {
        window.attachEvent("onload", init);
        }
        else
        {
        window.onload = init;
   }
}
</script>
</head>
<body>

<H1>Sample Progress Bar</H1>
<span id="percentage"></span>
<script type="text/javascript">
        var i=0;
        document.write("<table width='5%' border='1' style='border-color:black' > <tr>");
        document.write("<td><table >");

        for (i=1;i<=25;i++)
        {
                document.write(" <td id='td"+i+"' >&nbsp;</td>");
        }

        document.write("</table></td>");
        document.write("</tr></table>");
</script>
</body>

<script language="javascript">
        callOnLoad(init);
</script>

</html>

Copy the above code in a file and save the file as "sampleProgressBar.html" in your system. Then open the file in any browser to view the progress Bar. Modify the above code to suite your application needs.