Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Use JavaScript to Create a For Loop for HTML5 and CSS3 Programming

The standard for loop in JavaScript counts the values between 1 and 10. The “count to ten” button triggers the count()function for your HTML5 and CSS3 programming. Here's the code for count():

 function count(){
  output.innerHTML = "";
  for (i = 1; i <= 10; i++){
  output.innerHTML += i + "<br />";
  } // end for loop
 } // end count

Although the count() function clearly prints ten lines, it only has one line that modifies the output div. The main code repeats many times to create the long output.

  1. You can use the output var immediately.

    Because output is a global variable and it has already been created, you can use it instantly. There's no need to initialize it in the function.

  2. Clear the output.

    Set output.value to the empty string (“”) to clear the output. This will destroy whatever text is currently in the div.

  3. Start a for loop.

    The for loop is a special loop used to repeat something a certain number of times. For loops have three components: initialization, comparison, and update.

  4. Initialize your counting variable.

    A for loop works by changing the value of an integer many times. The first part of a for loop initializes this variable (often called i) to a starting value (usually 0 or 1).

  5. Specify a condition for staying in the loop.

    The second part of a for statement is a condition. As long as the condition is true, the loop will continue. As soon as the condition is evaluated as false, the loop will exit.

  6. Change the variable.

    The third part of a for statement somehow changes the counting variable. The most common way to change the variable is to add one to it. The i++ syntax is a shortcut for “add one to i.”

  7. Build a code block for repeated code.

    Use braces and indentation to indicate which code repeats. All code inside the braces repeats.

  8. Inside the loop, write to the output.

    On each iteration of the loop, add the current value of to the output div's innerHTML. Also add a break (<br/>) to make the output look better. When you add to an innerHTML property, you're writing HTML code, so if you want the output to occur on different lines, you need to write the HTML to make this happen.

  9. Close the loop.

    Don't forget to end the loop, or your program will not run correctly.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.