Core JavaScript

Animation - Moving Dot

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 AnimationLoop 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 if statements inside the function change the direction of the dot by changing the incremented value of the horirzontal position.

The two div elements, the gray background and the black dot, 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.

MovingDot.html

<!DOCTYPE html>
<html>
<head>
  <title>XoaX.net's Javascript Animation - Moving dot</title>
  <script type="text/javascript" src="MovingDot.js"></script>
</head>
<body>
  <div id="BkgdDiv">
    <div id="DotDiv">
    </div>
  </div>
</body>
</html>

MovingDot.js

var qpBkdg = null;
var qpBall = null;
var iHorizMove = 5;

function AnimationLoop() {
  var iBallWidth = parseInt(qpBall.style.width);
  var iBkgdWidth = parseInt(qpBkdg.style.width);
  var iCurrBallLeft = parseInt(qpBall.style.left);
  var iNewBallLeft = iCurrBallLeft + iHorizMove;
  var iNewBallRight = iNewBallLeft + iBallWidth;
  if (iHorizMove > 0) {
    if (iNewBallRight > iBkgdWidth) {
      iHorizMove = -iHorizMove;
      qpBall.style.left = iCurrBallLeft+iHorizMove+'px';
    } else {
      qpBall.style.left = iNewBallLeft + 'px';
    }
  } else {
    if (iNewBallLeft < 0) {
      iHorizMove = -iHorizMove;
      qpBall.style.left = iCurrBallLeft+iHorizMove+'px';
    } else {
      qpBall.style.left = iNewBallLeft + 'px';
    }
  }
  setTimeout(AnimationLoop, 20);
}

function Initialize() {
	qpBkdg = document.getElementById('BkgdDiv');
	qpBkdg.style.width = '400px';
	qpBkdg.style.height = '300px';
	qpBkdg.style.background = '#aaaaaa';
	qpBkdg.style.position = 'absolute';
	qpBkdg.style.left = '25px';
	qpBkdg.style.top = '35px';

	qpBall = document.getElementById('DotDiv');
	qpBall.style.width = '10px';
	qpBall.style.height = '10px';
	qpBall.style.background = '#000000';
	qpBall.style.position = 'absolute';
	qpBall.style.left = '20px';
	qpBall.style.top = '30px';

	AnimationLoop();
}

window.onload = Initialize;
 

Output

 
 

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