Lab 6: Programming Functions
FIT 100 Winter 2005

Key Words:function, method, procedure, form control, input, id, onchange, event handler, function call, function definition, function head, formal parameter, function body, variable, variable declaration, assignment operator, assign, getElementById(), value, text, string of characters, +, string concatenation, string, innerHTML.
See Wikipedia (http://www.wikipedia.org/) for a detailed description of the key words.

Preparation

You are required to have completed the objectives in Lab 5 before doing this lab.

Objectives

Remember to use the online resources! When you encounter a new HTML element, look at W3Schools XHTML tutorial and W3C's XHTML and HTML recommendations (see links at the end of this lab). When you encounter a Javascript function or want to find what you can do with an HTML element in you Javascript code, look at W3Schools Javascript tutorial and W3Schools DHTML/DOM (Dynamic HTML/Document Object Model) tutorial. You do not need to understand everything in their tutorials, but you should at least know where to find help.

A Javascript Program Using a GUI

In the previous lab you wrote some Javascript code within the HTML code of a web page. In this section you will learn how to use HTML to get information from the user through a graphical user interface (GUI) and how to use that information in your Javascript code to change the contents of a web page.  Call the file lab6.html.  One way to start would be to copy the file from the previous lab, rename the copy to something you like, and modify that new file.  Or make a new file and type in the basic HTML tags as usual.

  1. Start by adding a paragraph to your body element. This is HTML rather than Javascript, and does not come inside a <script> tag.  The paragraph should include a text asking for the user's first name followed by an input element (also called form control since it is widely used in web forms for users to fill out):
    <p>
    Your first name please:
    <input id="firstName" type="text" onchange="fixOutput()" />
    </p>

    This input element:

    Document (add comments), save, publish, validate, and view your enhanced document through a browser. Correct any errors.

  2. While viewing the file throught the browswer, if you enter some text in the text field and leave it (by pressing the Tab key or clicking outside the text field), nothing happens. This is because the Javascript function fixOutput() is not known by the browser yet. Compare this with the alert() function which the browser has built in.

    Functions are an important concept in programming, regardless of what language is used. A function is a description of steps defined in one place and used (or called) from another place in your code. It is very much like a recipe: you write it once, but can use/follow it over and over again (given you have the required ingredients). A function can also be used/called by other functions in the same way that you can write some base recipe that can be used in other recipes: a pie dough recipe can be used by many different pie recipies.

    Functions must be written, or defined before they can be used/called for the first time. This means that you should define all your functions in a file that will be loaded at an early stage. For HTML documents, a function is generally placed in the <head> tag (it can also be in a separate file with an extension of .js, which we won't do in this lab). 

  3. Define your fixOutput() function using the following:
    <script language="JavaScript">

    function fixOutput() {
    alert("Running function fixOutput()");
    }
    </script>
    This code belongs within the <head> section of the document.
  4. Every function definition in Javascript must begin with a function head or heading (not to be confused with the HTML <head> tag -- an unfortunate coincidence) that consists of:

    1. the word "function",
    2. a descriptive name of your choice (with some limitations) for the function,
    3. and parentheses that may (be do not have to) include a list of arguments, a.k.a formal parameters. The formal parameters can be used in the body of the function.

    After the head comes the function body, which includes an opening curly bracket "{", some content/statements, and a closing curly bracket "}".  We frequently will have occasion to say that something is "inside the body", meaning that it comes between those brackets.

  5. Save and reload your lab6.html in a browser. Enter some text in the input field and leave the field. When the cursor leaves the (changed) input field, the browser will call your fixOutput() function. The function will then run its code and, in this case, cause an alert window to appear!

    If this did not happen, check the following list of common errors:

    The list of common errors is something you should always check when you encounter an error or any strange behavior. Many programming errors result from spelling errors or from the the programmer using at an old version of their file (because s/he forgot to save after the latest changes).

When everything works as intended you can brag a little: You have just written a complete computer program that accepts user input through a graphical user interface (GUI) and gives feedback to the user. And you have done so by using a function, a feature that most beginners have problems with!

However, before you are done with the lab, your program should do something with the user's name and update the contents of the web page.

Enhancing your program

In northern Europe some thousand years ago people that called themselves nordbor (Swedish for "people who live in the North") went out on trips to "convince" other people to give them gold and other valuables. This behavior was given the term "gå i viking" ("Go on a long trip") which later made these people known as Vikings.

Today you can find Vikings and their decendants everywhere, and in many cases, they can be found by looking at their last name. For a long time, it was very common among Vikings to get their last names by combining their father's or their mother's first name with the word "son" or "dotter" (for daughter). It was more common for the Western Vikings (from Iceland) to follow the tradition for their daughters than for the other Scandinavian Vikings and, therefore, it is more common to see the Icelandic version of "dottir" than "dotter".

  1. Modify your fixOutput() function to show the message "I have some interesting news for you." instead of the rather dull old message. Verify that it works as intended.
  2. You will now write some Javascript statements that can extract the name from the input field and store it somewhere. "Somewhere" is usually a named place in the computers memory known as a variable. Think of a variable as a bucket (with a name) that is big enough to hold some information.

    Variables (like functions) are not known by the browser until they are described in Javascript code. They must, however, be declared before they exist.  Look back at Lab 5 to see variables in action: anumber, another and action were variables which you declared and used.

    At the beginning of the body of your fixOutput() function (on an empty line right after the opening curly bracket '{', and before the 'alert' statement), add the following statement:

    var firstName;

    This is a variable declaration.  The rest of the statements in the fixOutput() function can now use the "bucket"/variable named firstName to store things in. Note that variable name (like function names) cannot have spaces, which is why we capitalize "N" in "firstName". It makes the names easier to read.

  3. Add this on a line after the 'alert' statement (still before the closing '}' of the function):
    firstName = document.getElementById("firstName").value;

    This is quite complicated but can be understood by examining it in pieces. The entire statement has three parts:

    The assignment operator executes the expression on the righthand side and stores the result in the variable on the lefthand side. Or, put another way, the variable on the lefthand side is assigned the value calculated from the righthand side.

    The righthand side can be understood by reading it from left to right: "Use the document's getElementById() function, and once that is done, take the value from the result".

    You need to have some creativity to figure out what the document's getElementById() function does. Given an id, the function gets the corresponding element in the document. So the browser looks through your HTML document and tries to find an element that has an id attribute with the value "firstName". Go to your HTML document and you will see that you have an input element that has an id attribute with the value "firstName". Therefore, getElementById("firstName") will get this particular input element.

    The value located after getElementById("firstName") tells the browser to extract the value (text) that the user typed into the text field. The value, in this case, will be a name (a string of characters).

  4. Document (add comments), save, publish, validate, and try your program!

    Nothing new should happen. So how can you verify that everything works? One good way is to add an alert message that shows the entered name. Add the following statement to the end of the fixOutput() function body (i.e., on a line before the '}'):

    alert("Your name: " + firstName);

    Notice how you can use "+" to join (concatenate) two things together. In this case, you are concatenating a string of characters, "Your name: ", with the contents of the variable firstName (another string of characters). Expressions within parentheses are always executed first, like in mathematics. So the alert() function will, therefore, receive the concatenated result, and show the result in the alert window.

  5. Document (add comments), save, publish, validate, and try your program! When it works as intended you can remove the last alert() statement.

  6. As a final point, have your fixOutput() function change the contents of an element in your web page! Begin by ensuring that you have an element that you can refer to by its id. Add a paragraph in your lab6.html. It should be placed in the body element, right before the table element (footer) at the end:
    <p id="output">
    </p>

    Note that the element contains an id attribute, which you will use when you want to get the element using Javascript code.

    Add the following lines to the end of your fixOutput() function (inside the body):

    var elementToChange = document.getElementById("output");
    elementToChange.innerHTML =
    "If you where a <em>real Viking</em>, your son's last name would be " +
    firstName + "sson " +
    "and your daughter's last name would be " +
    firstName + "sdottir!";
  7. Save, publish, validate, and try your program. Fix any errors using the check list for common errors that was described earlier in the lab.
  8. To help a reader understand your code, you can add comments to it.  Comments do not affect how the Javascript executes.  One way to make a comment is to write something with // in front of it.  Everything from the // to the end of that line is ignored.  Write comments in the Javascript code explaining what each line of the fixOutput() function does. (Place the comment on a line by itself immediately above the line you are explaining.)  If you can figure out the Javascript in that last bit of code, you are doing good research! Answer questions like what is elementToChange and what is it for? What is the innerHTML for? Discuss the function with your fellow students! You can find information about innerHTML in the DOM section of W3Schools DHTML Tutorial.

HTML References

http://www.w3.org/

http://www.webmonkey.com/