Core JavaScript

Animation - Progress Bar

We can create a simple animation using a timed loop that is generated by recursive calls to the setTimeout(). The setTimeout() function is called with a function and a time passed in as parameters. The function that is passed in is the function that setTimeout() will call after the time interval has expired.

In the example code below, we pass in Loop and 20 so that the function AnimationLoop() is called after 20 milliseconds. Since AnimationLoop() calls setTimeout() at the end of its execution, it sets up a loop that is executed every 20 milliseconds. This loop creates a timed animation.

The statements inside the AnimationLoop() function increase the length of the bar by 1 pixel every time, until the maximum is reached. The the value is returned to zero via the modulus operator.

The two div elements, the gray background and the black bar, are accessed and styled via element ids in the Initialize() function, which is called in the beginning to trigger the animation loop.

Once these two files are created and saved in the same folder, we can double-click the file "MovingDot.html" to begin the animation, as shown below.

ProgressBar.html

<!DOCTYPE html>
<html>
<head>
  <title>XoaX.net's Javascript Recursive Animation Example</title>
  <script type="text/javascript" src="ProgressBar.js"></script>
</head>
<body>
  <div id="BkgdDiv">
    <div id="BarDiv">
    </div>
  </div>
</body>
</html>

ProgressBar.js

var qpBkdg = null;
var qpBar = null;
var iWidth = 0;

function Loop() {
	var iBkgdWidth = parseInt(qpBkdg.style.width);
	qpBar.style.width = iWidth+'px';
	iWidth = ((iWidth + 1) % iBkgdWidth);
	setTimeout(Loop, 20);
}

function Initialize() {
	qpBkdg = document.getElementById('BkgdDiv');
	qpBkdg.style.position = 'absolute';
	qpBkdg.style.width = '480px';
	qpBkdg.style.height = '50px';
	qpBkdg.style.background = '#aaaaaa';
	qpBkdg.style.margin = '30px';

	qpBar = document.getElementById('BarDiv');
	qpBar.style.position = 'absolute';
	qpBar.style.width = '0px';
	qpBar.style.height = '20px';
	qpBar.style.background = '#000000';
	qpBar.style.left = '0px';
	qpBar.style.top = '15px';

	Loop();
}

window.onload = Initialize;
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.