Lab 08: Programming Functions

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 08 before starting this lab.

Objectives

Remember to use the online resources! When you encounter a new HTML element, look at W3Schools HTML and XHTML tutorials, and W3C's HTML recommendations. When you encounter a Javascript function or want to find what you can do with an HTML element in your 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 section you successfully had a browser run your JavaScript code. 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.

  1. Make a lab8.html file with the usual HTML framework.

  2. Start by adding a paragraph to your body element. 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="firstNameField" type="text" onchange="fixOutput()">
    </p>

    This input element:

    Document (add comments), save, publish (i.e. copy into your student web site), validate, and view your enhanced document through a browser. Correct any errors.

  3. If you enter some text in the text field and then leave the field (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. By contrast, you didn't have to tell the browser about the alert() function -- the browser has that built in.

    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. It's good to get the browser to read them in early, before it starts laying out the page's body. For HTML documents, this means that the functions should be defined in the document's head.  It is often a good idea to define all your functions in a separate file, so you can reuse them from many pages.  If you put them in a file, then give the file the extension .js -- this will indicate it contains JavaScript code.  You can include the code from the file by using a src attribute in the script tag.

    Add this definition of the function fixOutput() in the document's head:

    <script type="text/javascript">
    function fixOutput() {
    alert("Running function fixOutput()");
    }
    </script>

    Every function definition in JavaScript must begin with a function head that consists of:

    After the head comes the function body, which includes an opening curly bracket "{", some content/statements, and a closing curly bracket "}".  (You'll note we're using the words "head" and "body" to describe parts of functions and also parts of HTML pages...)

  4. Save and reload your lab8.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 simple things like spelling errors or using at an old version of their file (due to forgetting 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 this section we'll be modifying and re-displaying the user's name.  Here's a little background on what we'll do to the name:

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 identified 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 spelling "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.  We used variables in lab 6 and 7 to give names to values.

    Variables (like functions) do not exist until they are declared in the JavaScript code. Unlike functions, variables do not need to be defined -- they do not need to have their value specified right away when they're declared.  (You can think of a function's body as its "value".)

    At the end of the body of your fixOutput() function (on an empty line right above the closing curly bracket '}'), 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 the 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 the following statement after your variable declaration:
    firstName = document.getElementById("firstNameField").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: "Call the document's getElementById() function with the argument "firstNameField", 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 "firstNameField". Go to your HTML document and you will see that you have an input element that has an id attribute with the value "firstNameField". Therefore, getElementById("firstNameField") will get this particular input element.

    The value located after getElementById("firstNameField") 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:

    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 lab8.html. It should be placed in the body of the page, right before the </body> end tag:
    <p id="output">
    </p>

    Note that the element contains an id attribute, which gives a name to the element that you will use when you want to refer to that particular element in your JavaScript code. 

    Now you can tell the browser to put new text right there in the paragraph called output.  Here's how:  Add the following lines to the end of your fixOutput() function (inside the function body):

    var elementToChange = document.getElementById("output");
    elementToChange.innerHTML =
    "If you were a <em>real Viking<\/em>, your son's last name would be " +
    firstName + "sson " +
    "and your daughter's last name would be " +
    firstName + "sdottir!";
    Why is that backslash in there? Without it, the browser would try to interpret the / as some HTML code right there while it's reading in the page head, not later when the JavaScript function is run.  The backslash "quotes" the following character, so the browser treats it as ordinary text while reading in the page.

  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. Write comments in the JavaScript code explaining what each line of the fixOutput() function does. (Place the comment immediately above the line you are explaining.) 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.

Turn in Word Document with link to your Lab 8

Due Date: Monday/Tuesday, November 5/6, before end of your scheduled lab.

HTML References

http://www.w3.org/

http://www.webmonkey.com/