Intro To Code Part 2

So far we have learned the basic information structures and control flow that can be found in almost any program in any language. Now we will learn how to break it into re-useable parts and allow the user to interact with it.

Intro To Code Part 1

Intro To Code Part 2

Interactivity

So far our webpage doesn't do much. It's just a list of words and definitions. It would help us learn Italian if we could guess the meaning of a word and then check if we are right. It should be more dynamic and interactive. We want a function that shows the English word if we click the Italian word. Then we can call that function when someone clicks a word.

An 'event' in coding is just that - a moment when something happens. Like cause and effect there are two parts to handling events:

  • The event or action itself, such as the user clicking something.
  • The outcome of the event. What happens when the user clicks the button can be defined in a function.

Functions

A 'function' is one of the most important concepts in programming. It is a set of instructions that can be re-used again and again from other parts of an application, rather than having to write the same bit of code over and over. It also enables us to package up a set of processes so that they can be called with a single command, which makes code more manageable.

Firstly, we need to understand how functions work. In the following code we use the 'function' keyword to declare the function and name it. It's like a mini-program that we can call from anywhere else in the program, as often as we like. You can see that we have declared two functions like this:

function listWords(){ ... }

and

function listTranslations() { ... }

and where we call the functions with the simple command listWords(); and listTranslations();

In this way you can break your code up into re-usable parts, and make your code more readable by using simple commands like 'listWords()' when you want to list words.

<html>
    <head>
        <title>Learn Code</title>
    </head>
    <body>
        <h1>Learn Italian</h1>
        <p>Welcome 
        </p>
        <p id="greeting">Your name will appear here. 
        </p>
        <p>To practice code we will write a simple app to help learn Italian.</p>

        <p>Remember these words: </p>
    
        <ul id="italian">

        </ul>
        
        <ul id="english">

        </ul>
    
        <script>
                var name = "Shelley";
                var ItalianWords = [];
                ItalianWords["ciao"] = "Hello";
                ItalianWords["gatto"] = "cat";
                ItalianWords["mangiare"] = "eat";
                ItalianWords["pasta"] = "pasta";
                
                document.getElementById("greeting").innerHTML = ItalianWords["ciao"] + " " + name;
                
                listWords();
                listTranslations();
                
                function listWords(){
                    var keysHTML = "";
                    for (var key in ItalianWords) {
                        keysHTML = keysHTML + "<li>" + key + "</li>";
                    }
                    document.getElementById("italian").innerHTML = keysHTML;
                }
                
                function listTranslations() {
                    var valuesHTML = "";
                    for (var key in ItalianWords) {
                        valuesHTML = valuesHTML + "<li>" + ItalianWords[key] + "</li>";
                    }
                    document.getElementById("english").innerHTML = valuesHTML;
                }
        </script>
    
    </body>
</html>

Check you understand: Create a function that sets the greeting and call it.

Events

Now we want to only run the function if the user takes an action. We need to create something for the user to click on and match the right function to that event. This is quite simple in Javascript. In the below code we have created an HTML paragraph that says "VIEW ENGLISH". Within the <p> tag we have added an 'onclick' attribute and set it to be the function "listTranslations()" that we created in the Javascript. All together it's as simple as

<p onclick="listTranslations()">VIEW ENGLISH</p>

Note that we also removed the command to "listTranslations()" from the Javascript, because we don't want to do that until the user clicks. We only want to 'listWords()' to show the Italian words.

When you open this in your browser you should see the Italian words. When you click 'VIEW ENGLISH' it should show the English translations.

    <html>
    <head>
        <title>Learn Code</title>
    </head>
    <body>
        <h1>Learn Italian</h1>
        <p>Welcome 
        </p>
        <p id="greeting">Your name will appear here. 
        </p>
        <p>To practice code we will write a simple app to help learn Italian.</p>

        <p>Remember these words: </p>
    
        <ul id="italian">

        </ul>
        <p onclick="listTranslations()">VIEW ENGLISH</p>
        <ul id="english">

        </ul>
    
        <script>
                var name = "Shelley";
                var ItalianWords = [];
                ItalianWords["ciao"] = "Hello";
                ItalianWords["gatto"] = "cat";
                ItalianWords["mangiare"] = "eat";
                ItalianWords["pasta"] = "pasta";
                
                document.getElementById("greeting").innerHTML = ItalianWords["ciao"] + " " + name;
                
                listWords();
                
                function listWords(){
                    var keysHTML = "";
                    for (var key in ItalianWords) {
                        keysHTML = keysHTML + "<li>" + key + "</li>";
                    }
                    document.getElementById("italian").innerHTML = keysHTML;
                }
                
                function listTranslations() {
                    var valuesHTML = "";
                    for (var key in ItalianWords) {
                        valuesHTML = valuesHTML + "<li>" + ItalianWords[key] + "</li>";
                    }
                    document.getElementById("english").innerHTML = valuesHTML;
                }
        </script>
    
    </body>
</html>

Check you understand: Don't list the Italian words when the page loads. Instead make a 'VIEW ITALIAN' paragraph and list the Italian words when the user clicks it.

Sending and Returning Variables

You can also send information (input variables or parameters) to a function, and get information out of it. This is useful if you want to run the function on different information at different times, and get an answer back to store in a variable to use in other parts of your application. A simple example of a function is 'addition'. We could send any two numbers to an addition function, which adds them up and gives an answer back. In our example we might want to use the same function to list words in German or Chinese.

To keep it simple for now though, look at the 'return' command in the following code. The listWords() function now 'returns' the value of 'keysHTML', instead of setting the 'italian' HTML list. We set the value of the 'italian' HTML list to be whatever is returned by the listWords() function like this:

document.getElementById("italian").innerHTML = listWords(ItalianWords);

We have also added a function called 'showTranslation(word)'. Inside the brackets we are creating an input variable that will be manipulated in the code. In this case it is just expected to be a keyword so that we can 'return' the corresponding translation of that word. Notice that we set the greeting to say "Hello" by using the function to translate "ciao" into English.

So far this is just to demonstrate various ways functions can be used.

    <html>
    <head>
        <title>Learn Code</title>
    </head>
    <body>
        <h1>Learn Italian</h1>
        <p>Welcome 
        </p>
        <p id="greeting">Your name will appear here. 
        </p>
        <p>To practice code we will write a simple app to help learn Italian.</p>

        <p>Remember these words: </p>
    
        <ul id="italian">

        </ul>
        <p onclick="listTranslations()">VIEW ENGLISH</p>
        <p id="english">

        </p>
    
        <script>
                var name = "Shelley";
                var ItalianWords = [];
                ItalianWords["ciao"] = "Hello";
                ItalianWords["gatto"] = "cat";
                ItalianWords["mangiare"] = "eat";
                ItalianWords["pasta"] = "pasta";
                
                document.getElementById("greeting").innerHTML = showTranslation("ciao") + " " + name;
                
                document.getElementById("italian").innerHTML = listWords(ItalianWords);
                
                function listWords(){
                    var keysHTML = "";
                    for (var key in ItalianWords) {
                        keysHTML = keysHTML + "<li>" + key + "</li>";
                    }
                    return keysHTML;
                }
                
                function showTranslation(word) {
                    return ItalianWords[word];
                }
        </script>
    
    </body>
</html>

Check you understand: Create a function called 'showGreeting' that accepts two input variables and returns the full greeting. Use it to set the value of the 'greeting' paragraph.

Putting it all together

In the next example we have changed a few things around to get the desired interactive behaviour. When we loop through the Italian words to create a list, we add to each of them an onclick event connected to the showTranslation(word) function. As we do so we put the Italian word as the input variable. The HTML list generated would now look like this:

  • ciao
  • gato
  • mangiare
  • pasta
  • Now when you click on each item in the list it will call the showTranslation function and pass it the specific Italian word as the input variable. The showTranslation function will then look up the English word and set the paragraph with the id 'english' to show the specific English word. Now you can click the Italian words one at a time to see the translation.

        <html>
        <head>
            <title>Learn Code</title>
        </head>
        <body>
            <h1>Learn Italian</h1>
            <p>Welcome 
            </p>
            <p id="greeting">Your name will appear here. 
            </p>
            <p>To practice code we will write a simple app to help learn Italian.</p>
    
            <p>Remember these words: </p>
        
            <ul id="italian">
    
            </ul>
            <p onclick="listTranslations()">ENGLISH:</p>
            <p id="english">
    
            </p>
        
            <script>
                    var name = "Shelley";
                    var ItalianWords = [];
                    ItalianWords["ciao"] = "Hello";
                    ItalianWords["gatto"] = "cat";
                    ItalianWords["mangiare"] = "eat";
                    ItalianWords["pasta"] = "pasta";
                    
                    document.getElementById("greeting").innerHTML = ItalianWords["ciao"] + " " + name;
                    
                    listWords();
                    
                    function listWords(){
                        var storeHTML = "";
                        for (var key in ItalianWords) {
                            storeHTML = storeHTML + "<li onclick='showTranslation(\"" + key + "\")'>" + key + "</li>";
                        }
                        document.getElementById("italian").innerHTML = storeHTML;
                    }
                    
                    function showTranslation(word) {
                        document.getElementById("english").innerHTML = ItalianWords[word];
                    }
            </script>
        
        </body>
    </html>
    

    Check you understand: Change this whole application around. Add the ability to list English words and when you click on each one, show the Italian word. Give the user the option of doing it either way - listing English words for clicking, or listing Italian words for clicking.

    Conclusion

    As a result of this course you should now have a basic understanding of the following concepts, and how to apply them.

    • variables
    • conditional statements
    • arrays
    • associative arrays
    • loops
    • functions
    • events

    To learn programming it is useful to work on a specific project. Having to solve problems leads you to learn more and more about a language and software techniques. Software development projects usually fall into one of several focus areas. If you would like more guidance, look at the Skill Focus Areas for a field that best suits your interests, at Online Tutorials and Tools and IDEs. All programmers, at any stage in their careers, continue to use search engines to find things in language references, to figure out what causes error messages or find solutions that others have found to problems and scenarios.