Now that we have random positioning and coloring settled, we need to start looking at a way to animate the box moving across the screen. Once upon a time, I would’ve just used Flash to make all this work, but vast improvements in HTML, CSS, and JavaScript have really (thankfully) eliminated the need to use Flash for this kind of work. There are now two main ways to animate objects on a web page: one using CSS and one using JavaScript (or jQuery). We’ll start by looking at the CSS method.
I made a few minor changes to the previous HTML & JavaScript files so that it draws 2 div containers, each a random color, and places them at some random Y position along the left side of the screen. For visual clarity, I made one square 300px and one 200px:
iteration2.js
function makebox() { var top1=Math.random(); var top2=Math.random(); top1=top1*100; top2=top2*100; document.getElementById("box1").style.top=top1+"px"; document.getElementById("box1").style.backgroundColor=getRandomColor(); document.getElementById("box1").style.display="block"; \document.getElementById("box2").style.top=top2+"px"; document.getElementById("box2").style.backgroundColor=getRandomColor(); document.getElementById("box2").style.display="block"; }
iteration2.html
<html> <head> <script type="text/javascript" src="iteration2.js"></script> <style type="text/css"> div { animation-name: example; animation-duration: 4s; animation-iteration-count: infinite; } @keyframes example { 0% {left:0%;} 100% {left:100%;} } #box1 { width:200px; height:200px; background-color:red; display:none; position:relative; } #box2 { width:300px; height:300px; background-color:red; display:none; position:relative; } </style> </head> <body onload="makebox();"> <div id="box1"></div> <div id="box2"></div> </body> </html>
In the CSS section of the HTML document, we see that div containers in this document will be animated and that animation will have a duration of 4 seconds, repeating infinitely. The @keyframes parameters define two keyframes for this 4 second animation: 0% (the beginning) and 100% (the ending). We could add other keyframes in between, but for simplicity, we’ll just stick with the requisite two.
0% {left:0%;}
defines the first keyframe of the animation, placing the object to be animated at the left edge of the screen.
100% {left:100%;}
declares that the last keyframe of the animation will see the object at the right edge of the screen.
Note that the animation is the same for every iteration of the loop. In order to see different combinations of colors and starting positions, you’ll need to refresh the page.