JavaScript Tutorial 10
functions
OK. So you've learned how to make a page do all sorts of stuff when it loads. But, you've reached the point in your JavaScript maturity when you realize that sometimes you want your scripts to wait for something to happen before they execute. You've
e learned about events already, and you know that you are going to use events to trigger your script. But, you don't yet know how to keep your scripts from running when the page loads.
Well, the answer is "functions". Functions enclose JavaScript code and allow you to call for the execution of that code in much the same way that you call methods. To define a function, (THAT'S
RIGHT YOU define functions) you must do a few simple things.
The first involves proper placement of the script. Functions, like all JavaScript components, must be located inside script tags and comments. I always place mine in the head, and so do most JavaScript programmers. I would suggest that you do the same, however you could place them anywhere.
Change your document to look like this:
Click here to maximize
<html>
<head>
<title>
(Your title)
</title>
<script language=javascript>
<!--
function doIt(){
value1 = prompt("Enter your first name:","");
value2 = prompt("Enter your last name:","");
finalValue = value1 + " " + value2;
window.document.answerform.answer.value = finalValue;
}
//-->
</script>
</head>
<body bgcolor=white>
<form name=answerform>
<input type=text size=35 name=answer><br>
<input type=button value='Do It' onclick=doIt();>
</form>
</body>
</html>
|
What we have here is basically that same script that (in Tutorial 5) used to run automatically, but with a few minor changes. First, you moved your old script - script tags and all - into the head. Then you inserted the stuff in blue - "function doIt(){" and "}" around your script. Finally, you put a button input which when clicked - using the "onclick" event - calls the function.
Let's analyze these changes more closely. The first line in blue says " function doIt(){". The first part tells the browser that you are defining a new function. The next part, "doIt" names the function that we are defining.
Now it gets interesting. The parentheses - "()" - serve an important purpose. Items placed inside the parentheses represent parameters that are passed to the function by whatever event
has called it. In the case of our current example, we are not passing any parameters so
it is empty. Don't worry, we'll talk about parameters later in this tutorial.
The next thing you see on that line is an open bracket "{". This tells the browser that we are beginning to define the contents of our function. If you look a few lines below, you will see a close bracket "}" in blue. This tells the browser that we have completed the definition of our script.
Finally, the button input, when clicked (via onclick), calls the doIt() function. Notice that the function caller defined on this line - doIt() - matches precisely the capitalization and spelling of the function that you have defined, and includes the parentheses.
This is important to remember. Function names ARE case sensitive. So, when you call your functions, remember to use the correct spelling and case.
Now, click 'Preview'.
When you click the 'Do It' button, the function should have been called and acted very much like it did when we had it run automatically when the page loaded.
| Multiple-Unrelated Functions |
The first thing that I need to say is that you can have multiple scripts within one document that do completely unrelated things. What do I mean? Well, I mean that on one web page,
you can have one script that does one thing, and another that does some completely unrelated thing. The way that you can do this is by having multiple functions.
Perhaps the best way is to show you. Make your document look like this:
Type the following into CodeRunner below:
Click here to maximize
<html>
<head>
<title>
(Your title)
</title>
<script language=javascript>
<!--
function askIt(){
value1 = prompt("Enter your first name:","");
value2 = prompt("Enter your last name:","");
finalValue = value1 + " " + value2;
window.document.answerform.answer.value = finalValue;
}
function showIt(){
alert(window.document.inputform.messageinput.value);
}
//-->
</script>
</head>
<body bgcolor=white>
<table border=1>
<td>
Ask Names Form<br>
<form name=answerform>
<input type=text size=35 name=answer><br>
<input type=button value='Do It' onclick=askIt()>
</form>
</td>
</table>
<table border=1>
<td>
Display Field Value Form<br>
<form name=inputform>
<input type=text size=35 name=messageinput><br>
<input type=button value='Do It' onclick=showIt()>
</form>
</td>
</table>
</body>
</html>
|
You've seen both of these functions before, just with different function names. The askIt() function asks your first and last names and then combines them and puts them into a form input.
The showIt() function has you type something into the form input and displays that value in an alert box.
Go try them out, and then come back to see why this is possible.
What you haven't seen before is two or more separate functions within the same document. This is completely appropriate. In fact, as you probably noticed, they even share the same script tags and comment tags. What separates them from one another is their independent function definitions and unique function names. That's it.
No matter what your script does, it can always share a parent document with another function as long as it has these two traits to distinguish them from one another. That's all there is to having multiple functions in a document.
Parameters are one of the things that add convenience and functionality (pun intended) to functions. Let's start by discussing a "real world"
example.
Pretend you are sending mail to a friend. That mail might be
might be a letter, a package, or a
postcard. All of these items go to the PostOffice after you send it by putting it into a mailbox. The PostOffice probably does something different with your mail depending on whether it's letter, a package, or a
postcard. For instance, the PostOffice might weigh a package, before it is delivered. I know it's reaching,
but let's analyze this process in JavaScript:
(Just remember that we are pretending for now)
Suppose that postoffice() is a function we are defining to handle mail. Pretend also that onSend is an Event Handler that
executes postoffice when someone drops mail into the mailbox. (i.e. our input type is mailbox)
Finally, suppose the only mail we can send are letters, packages, or
postcards. Here is a diagram of what we are doing:
Here is what the JavaScript code might look like:
<head>
<script language=javascript>
<!--
function postoffice(mail){
if (mail = ="package") {
mailman.weigh(mail);
}
mailman.deliver(mail);
}
//-->
</script>
</head>
<body bgcolor=white>
<form>
<input type=mailbox onSend=postoffice("letter"); value="To Mom"><br>
<input type=mailbox onSend=postoffice("package"); value="a present"><br>
<input type=mailbox onSend=postoffice("postcard"); value="from Rome"><br>
</form>
</body>
|
notice that we are pretending that we have a mailman object at our disposal that has the weigh and deliver methods in it.
You see? Now the function postoffice(mail) can handle
different input values (like "package") through the parameter mail. . (The parentheses after the function name is called the Parameter Clause). Think of
the parameter mail
as a box that carries input values like "letter" into the function
postoffice.
There are some more things here which may be new to you. Look inside of the postoffice function-- We used an if statement to check and
see if the input value was a "package". If
the input value is equal to "package" then
the mailman weighs it! But notice that the mailman delivers
all of the mail.
Also notice that there is a double equals sign "==" in the if statement.
(it wasn't a typo). The double equals sign is a comparison operator that says
"is it equal?" and returns either TRUE or FALSE (depending of course
on whether it is true or false). Then the stuff inside the { and } after the
if is executed only if the comparison is TRUE, otherwise it just skips that
step. There is a whole tutorial on if statements coming later.
To illustrate the utility of using parameters, let's do this same example without parameters. Before, we had one convenient place to
take our mail -- the postoffice. Now what if we had to take "letters" to one place (the letteroffice), and
"packages" to another place (the packageoffice), and "postcards" to yet another place (the postcardoffice)? This is what JavaScript would be like without parameters. In our example, without parameters, we would have to make
a different function for each type of input value. like this:
<head>
<script language=javascript>
<!--
function letteroffice(){
mailman.deliver();
}
function packageoffice(){
mailman.weigh();
mailman.deliver();
}
function postcardoffice(){
mailman.deliver();
}
//-->
</script>
</head>
<body bgcolor=white>
<form>
<input type=mailbox onSend=letteroffice(); value="To Mom"><br>
<input type=mailbox onSend=packageoffice(); value="a present"><br>
<input type=mailbox onSend=postcardoffice(); value="from Rome"><br>
</form>
|
In this case it was just a little more convenient to use parameters. (Saved travel time to the three different offices. ha!) There are cases which
cannot be done without parameters.
Okay we are done pretending, let's write some real JavaScript!
The following example will put buttons on a page that all run the same function when
they are clicked. The format for this example is exactly the same as for the PostOffice
example -- the only difference is that it uses methods which actually exist in JavaScript (i.e. alert and prompt).
Type the following into CodeRunner below:
Click here to maximize
<head>
<script language=javascript>
<!--
function doIt(messages){
if(messages=="Message2") {
window.prompt(messages);
}
window.alert(messages);
}
//-->
</script>
</head>
<body bgcolor=white>
<form>
<input type=button onclick=doIt("Message1") value='Click First'><br>
<input type=button onclick=doIt("Message2") value='Click Second'><br>
<input type=button onclick=doIt("Message3") value='Click Third'><br>
</form>
</body>
|
Click 'Preview' and try all three buttons.
See how we used the function caller doIt() to pass an input value at run time to the script? And then how that value was held by the parameter named messages so that when it was called by the alert method, it displayed the correct message? You should also notice that when we clicked the second
button it did more than the other two. That is because of the if statement in the
function doIt.
This works for as many parameters as you want. All you have to do is add a
parameter name in the parameter clause for each value that you wish to pass.
To add another, make these changes to your script (change the stuff in red):
Type the following into CodeRunner below: Click here to maximize
<head>
<script language=javascript>
<!--
function doIt(message,message2){
alert(message);
alert(message2);
}
//-->
</script>
</head>
<body bgcolor=white>
<form>
<input type=button value='Message1' onclick=doIt("Message1","Message4")><br>
<input type=button value='Message2' onclick=doIt("Message2","Message4")><br>
<input type=button value='Message3' onclick=doIt("Message3","Message4")><br>
</form>
</body>
|
Go try it.
You no doubt noticed the obvious changes, but I need to make a point of one of them. Did you notice the comma between both parameters, both in the function definition and in the function caller?
You must separate all parameters by commas. Other than that, you can use as many parameters as you want.
|