As you saw in lecture,
you can define your own JavaScript functions. Such functions are called
user-defined, as opposed to predefined functions which you get
from a library, such as the prompt() function.
What is important to know about user-defined functions:
Below is an example of a user-defined function to convert distance in feet, to distance in meters. This function, after computing the result, prints it in on the page.
<HTML> <!-- Wendy Wellesley cs110 11/11/07 --> <!-- Converts distance in feet to distance in meters --> <!-- using a function that computes and displays the distance ----> <HEAD> <TITLE> Feet to Meters </TITLE> <SCRIPT TYPE="text/JavaScript"> function displayMeters(feet) { // the function takes distance in feet // and writes the conversion in the document document.write("<P>You entered " + feet + " feet.<BR>"); // meters is a local variable: var meters = feet * 0.3048; document.write("That's equivalent to " + meters + " meters."); } </SCRIPT> </HEAD> <BODY> <SCRIPT TYPE="text/JavaScript"> var distance_in_feet = prompt("Please enter the distance measured in feet", ""); displayMeters(distance_in_feet); distance_in_feet= prompt("Give me one more - distance in feet -"); displayMeters(distance_in_feet); </SCRIPT> </BODY> </HTML>
Carefully study the example above. Answer the following questions:
Notice that the function above uses a local variable meters.
Click here to run the example.
OldMac.html
which you will create on your Desktop.
OldMacVerse() that
displays one verse of the Old MacDonald song.
Your function should have two arguments, one for the animal, and one for its sound.
The resulting page should look something like this old macdonald page. Of course, feel free to use any animals/sounds you would like! Also, give the viewer of your page the chance to input their favorite animal and sound, creating a dynamic page
<HTML>
<HEAD>
<TITLE> Old MacDonald and New Functions!</TITLE>
<SCRIPT TYPE="text/JavaScript">
//Define function in the HEAD part of your document:
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT TYPE="text/JavaScript">
// Here is one call to the function, using specific values for the arguments:
OldMacVerse("cow", "moo");
//Call your function several more times.
//Ask the user for an animal and a sound,
//and call the function with what you get:
</SCRIPT>
</BODY>
</HTML>
Your next task is to write a function that calculates a restaurant tip. In this version, tips are always 15 percent.
displayTip. It will take one argument, namely the
amount of the bill.
parseFloat to convert the result of
the prompt to a number. The result could be like this flexible 15 tip page
If you have more time, here are some more exercises to try.