Learn for-loops

Overview

Learn about using for-loops in a browser. We have been writing code at the command line with node. But how do we use the same code in a browser? This assignment is related to the ListButton assignment.

Create Directory

HINT: It should be easy for you to open up other HTML files you have created to help you flesh out some of the sections, such as the footer. For me, at least, it is helpful to build up a set of reference files that I can turn to when I need reminders about how to write code.

Button and Unordered List

Create a button and an unordered list. Here is a reminder of how we created a button in a previous assignment.

                                  
    <button id="set-text" type="button">Set Text</button>
                
            

Change the id to run-for-loop and the content to to Run for Loop.

Create a lib directory

Sometimes we have files that we use in multiple places in our code. One such a file is elf-code.js from the ListButton assignment. Let's move that file to a location where all our projects can access it.

git mv ListButton/elf-code.js lib/.

Create a file called index.js in our for-loop directory.

Link our JavaScript files into for-loop/index.html.


    <script src="../lib/elf-code.js"></script>
    <script src="index.js"></script>
            

In index.html also add an unordered list


    <ul id="my-list"></ul>
            

Call Loop

In index.js let's run a for loop and display it in our HTML file.


    window.onload = () => {
        const listButton = document.getElementById('run-for-loop');
    
        listButton.onclick = () => {
            const myList = document.getElementById('my-list');
                // WRAP THE NEXT LINE IN A for-loop that iterates over a variable named i. 
                // The loop should iterate 5 times (count from zero to five).
                elfCode.appendToList(myList, i);
                // END LOOP
        }
    }                    
            

Turn it in

Push your work and provide a link to your running for-loop code on your GitHub Pages site.