For-loop example
For JavaScript beginners
by akmiecik
HTML
<p>The script is a loop that makes a box each time the loop runs.
When the variable <em>i</em> is an even number, the box color is changed from the default color that is in the CSS (using modulus).</p>
CSS
body {
font-family: Calibri, sans-serif;
}
div {
float: left;
width: 25px;
height: 25px;
margin-top: 4px;
margin-left: 4px;
background: #ff0;
}
/* try changing 25px to a different number (twice) */
JavaScript
// try changing the number to 100
for (i = 1; i <= 10; i++) {
var box = document.createElement("div");
// modulus used below to determine if i is an even number
if ( i % 2 == 0) {
box.style.backgroundColor = "#00f";
}
document.body.appendChild(box);
}