Previous Contents Next
4. Event Handlers and Functions

When coding scripts, two decisions you must make are (1) where to put the scripts? and (2) how to package the scripts? In previous examples we have simply shown arithmetic and string expressions, but have not indicated exactly how and where they appear in an HTML document. We turn to these issues now.

Script Locations

The locations of scripts are pretty much determined by when they will be used. If the script is to be run when the page is opened, then it normally appears within the <HEAD> section. This would be the case, for example, of a welcome message. The script for the Alert box that was displayed when you arrived at this page appears in the <HEAD> section and was run automatically when you opened the page:

<HEAD>
<TITLE>4. Event Handlers and Functions</TITLE>

<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
alert("\nWelcome to the topic: \"Event Handlers and Functions.\"\n\nClick 'OK' to continue.")
//-->
</SCRIPT>

</HEAD>

Another location for such self-running scripts is at the beginning of the <BODY> section. The point is that scripts are run as they are encountered when your document is loaded. The above script statement to display the modification date at the top of this page must appear before the page is loaded so that it can be displayed first. Therefore, it must appear in the <HEAD> section. In fact, any script that writes to the page must go in the <HEAD> section. The Alert box, on the other hand, can be coded anywhere in the document. The script does not write directly to the page; therefore, it can appear anywhere to be run before, during, or after page loading. The main decision is whether or not the script will write to the page. If so, it goes in the <HEAD>; if not, it can go just about anywhere.

Event Handlers

Most scripts are not self-running. They are executed in response to users' actions: clicking on buttons, filling in forms, and the like. There are, in fact, specific actions that can trigger scripts and specific script commands that respond to these actions.

JavaScript provides ten commands, called event handlers, that run scripts when particular events take place. The following table lists and describes these handlers and the HTML tags with which they are associated.

Event Handler Event
onabort The user stops an image from loading, by clicking on the Stop button, for example. Works with the <IMG> tag.
onblur A form element "loses focus"; for example, the user clicks outside a field or tabs to another field without changing its value. Works with <INPUT TYPE="TEXT">, <TEXTAREA>, and <SELECT> tags.
onchange The user clicks outside or tabs from a form element (it loses focus) and the value of the element has changed. Works with <INPUT TYPE=TEXT>, <TEXTAREA>, and <SELECT> tags.
onclick The user clicks on a button or link. Works with <INPUT TYPE="BUTTON" >, <INPUT TYPE="CHECKBOX">, <INPUT TYPE="RADIO">, <INPUT TYPE="RESET" >, <INPUT TYPE="SUBMIT">, and <A HREF= > tags.
onerror An image cannot be loaded. Works with the <IMG> tag.
onfocus A form element "gains focus"; for example, the user clicks inside a field or tabs to a field. Works with <INPUT TYPE="TEXT">, <TEXTAREA>, and <SELECT> tags.
onload The page has finished loading into the browser or an image has finished loading into the document. Used with <BODY>, <FRAMESET>, and <IMG> tags.
onmouseover The user points to (moves the mouse over) a link. Works with the <A HREF= > tag.
onsubmit The user clicks on an <INPUT TYPE="SUBMIT"> button.
onunload The current page is unloaded (replaced by a new page). Works with the <BODY> and <FRAMESET> tags.


 

The onclick and onsubmit event handlers work well. The others work with varying degrees of success-- mostly NOT--under Navigator 3.0 and Internet Explorer 3.0. Even those that work adequately work just adequately, often introducing confusion by their unexpected actions or making it seem difficult to do a simple task. Some just don't do anything very useful. For these reasons, we will focus attention on onclick and onsubmit, leaving you to experiment with the others. Not a lot can go wrong when the user only needs to click a button. We'll discuss these event handlers as needed in the various examples throughout this tutorial.

Inline Scripts

Event handlers and their associated scripts can appear within HTML tags. For instance, a common way to trigger a script is a mouse click on a button. The following button and associated script display an Alert box similar to the one you saw when you opened the page. In this case, though, the script is run when you click the button.

<FORM>
<INPUT TYPE=BUTTON VALUE="Alert Message"
onclick="alert('\nYou just clicked on the button.')" >
</FORM>


The button, of course, is created with an <INPUT TYPE=BUTTON> tag as part of a <FORM> tag. Embedded within the <INPUT> tag, though, is the onclick event handler that displays the Alert box. When event handlers are coded within tags, the associated script to be run must be enclosed in quotes: onclick = "...script goes here...".

The alert Command. While we're at it, let's take a quick look at the syntax of the alert command since we will be using it often on this page to display output. Its general format is

alert ("literals" | variables | +)

The keyword alert is followed by the output to be displayed, enclosed in parentheses. You can display literal text (enclosed in quotes) and/or variables, concatenated with the "+" string operator: ("...text..." + var1 + "...more text..." + var2). You can even display a formula: (10 + 20 - 30) . Also, if you wish to include returns within your message, you can use the special characters "\n". A single \n is a line break; the pair \n\n is a paragraph break.

In the previous example, you'll note that the onclick script is enclosed in regular quotes ( " ), while the literal text of the alert command is enclosed in apostrophes ( ' ) --single quotes:

onclick="alert ('\nYou just clicked on the button.')"

If you have quotes embedded within quotes, then you must alternate between the two to keep from confusing JavaScript about their pairings.

Although the above script contains only a single command, you can stack together as many JavaScript statements as needed, separated by semicolons, within an event handler:


<FORM>
<INPUT TYPE=BUTTON VALUE="Calculate"
onclick="
var X = 10;
var Y = 20;
var Z = 30;
var Answer = X + Y + Z;
alert('\nThe total of X + Y + Z is ' + Answer) "
>
</FORM>


Including multiple script statements within HTML tags, however, can get confusing, leading to typing mistakes and error-prone code; plus, it can make your HTML code that much more difficult to read and understand. A much cleaner way of writing scripts is to use JavaScript functions.

Script Functions

A JavaScript function is a separate piece of code designed to perform a specific processing action. It is identified by a name and can be called upon to perform its processing from other script commands. The following script, for example, is a function that performs the calculations and displays the Alert box that was coded above as part of the "Calculate" button:

<SCRIPT>
function Calculate( )
{
    var X = 10
    var Y = 20
    var Z = 30
    var Answer = X + Y + Z
    alert ('\nThe total of X + Y + Z is ' + Answer) " >
}
</SCRIPT>


Once a function is created, it can be used (called) from anywhere in your HTML document to perform its processing. We can create a button, for instance, whose onclick event handler calls this function:

<FORM>
<INPUT TYPE=BUTTON VALUE="Calculate"
onclick="Calculate( )" >
</FORM>


The event handler need only to identify the function to call: Calculate( ) , in this example. All of the processing takes place within the function.

Called functions can appear anywhere in the HTML document and should appear prior to the event handler that calls them. Typically they appear close to the coding of the event handler. However, if they are called from more than one event handler, they can be placed in the <HEAD> section or at the top of the <BODY >section. Some people like to stack all functions in one place so that they are isolated and easily identified within the HTML document. A single script appearing anywhere in your document--or groups of scripts stacked together--must, of course, be enclosed within <SCRIPT> tags.

Function Syntax

The general format for the scripting of a function is

function FunctionName ( )
{
    script commands
}

The keyword function is followed by a name you assign to the function. This name follows the naming conventions for variables. It can be any name, although you should name it something meaningful. It is common to capitalize the name, but it's not really necessary. The name is followed by open and close parentheses. We'll see what can go between these parentheses in a few moments. They have to appear, though, even if not enclosing anything.

The JavaScript statements that comprise the function are placed between open and close braces: { and }. The braces don't have to be on separate lines, like above; they just have to surround the statements. Also, it is common to place each statement on a separate line. You'll eventually develop your own style of coding functions and settle on an appearance that works for you. Again, don't forget that functions must be enclosed within <SCRIPT> tags.

Passing Parameters to Functions

The great convenience of functions is that a script needs to be coded only one time, even if you intend to use it over and over. All the following buttons, for example, call the "Calculate" function that is shown above and that appears in this document. It was not necessary to code a separate script for each button. The buttons simply call the single function through an onclick command embedded in each.

Of course, you won't often need to run the identical script over and over. You might, however, want to perform the same processing, only on different data. And here is where the real power of functions comes in, and where you fill in the space between the parentheses. You can send different values to a function, and it will return different results using the same processing.

Here is a simple example. The first of the following two functions is designed to accept two numbers passed to it from some event handler. The function adds the numbers together and sends the result back to the event handler. The second of the functions displays in an Alert box whatever message is passed to it.


<SCRIPT>
function Add (First, Second)
{
    var Answer = First + Second
    return Answer
}

function Show (Message)
{
    alert ("The answer is " + Message)
}
</SCRIPT>


In the first line of the function named "Add," the items appearing between the parentheses and labeled "First" and "Second" are called the arguments of the function. These act like variables in that they represent storage areas where two values appear. The idea is that, when this function is called, it will be passed two data values that will be accessible by the function through these names. Once the function is called and the data values are passed to it, the function can involve the values in its processing. In the example, variable First is added to variable Second, with the result placed in variable Answer. The names assigned to the arguments and variables of a function follow the naming conventions of standard variables. The last line of the function returns the calculated Answer to whichever event handler called the function. The return statement must be there or the function would simply perform the calculation and then do nothing. Normally, you want to get something back from a function.

In the second function, named "Show," an argument called "Message" receives a value. The alert command in the function then displays this value in an Alert box. Nothing is returned to the calling statement.

Now, a general-purpose function exists to add two numbers together (Wow!); and a function exists to display a message in an Alert box. So, what do you do with them? Well, let's pass them some numbers and see what happens.

The following string of buttons contain onclick event handlers that (1) pass two numbers to the Add() function and (2) send the returned answer to the Show() function for display.

The scripts of the event handlers in all the buttons are similar. The coding for the first one is shown below (the commands are coded here on different lines for ease of reading, but the entire <INPUT> tag could be coded across a single line):

<FORM>
<INPUT TYPE=BUTTON VALUE="Add 5 + 5"

onclick="
    var A = 5;
    var B = 5;
    var Sum = Add (A, B);
    Show (Sum) "
>
</FORM>

The statement,

var Sum = Add (A, B);

creates a variable called Sum to which is assigned the result of calling the Add() function. The function is called by giving its name (Add) and is passed two values, or parameters, by enclosing them in parentheses. In the current case, parameters A and B, containing the values 5 and 5, are passed. When the function finishes, recall, it returns a value (10 in this case) that is assigned to Sum. What you need to remember is that the parameters passed by the calling statement are associated with the argument names in the receiving function. That is, parameter A is matched up with argument First; parameter B is matched up with argument Second. The names of the parameters and arguments are, in fact, irrelevant to the working of the function. What matters is that the number and order of parameters and arguments are identical.

Next, in the statement,

Show (Sum)

the parameter Sum is sent to the function named Show. (Sum contains the value 10 in this case.) Show() receives the parameter as argument Message, which it displays in an Alert box. Again, the name of the parameter and the name of the argument don't have to match, but the number of values sent does.

There is a shortcut way of coding this event handler:

<FORM>
<INPUT TYPE=BUTTON VALUE="Add 5 + 5"
onclick="A=5; B=5; Show ( Add ( A, B ) )" >
</FORM>

This shows that function calls can be contained within fuction calls. As in mathematical operations, the inner parentheses are cleared first. So, the Add() function is called first and its returned value is the parameter for the Show() function.

You can pass literals as well as variables. We could have coded the call as

<FORM>
<INPUT TYPE=BUTTON VALUE="Add 5 + 5"
onclick="Show ( Add ( 5, 5 ) )" >
</FORM>

since we knew the actual values that were going to be passed to the Add() function. In this case, still, the values 5 and 5 are received by the function as arguments First and Second.

There is one important fact to note about passing values to functions. You don't pass the actual variable or literal; you pass a copy of it. So, even if a function changes the value of a variable passed to it, it does not change the original variable; it changes only the copy received by the function.

The Scope of Variables

Any variables defined inside a function are local to that function. This goes also for variables passed to it. What this means is that a function's variables are recognized only by the function. You cannot refer to them from other scripts; they are undefined outside the function.

One advantage is that it is impossible to tinker with a function's variables from anywhere else in your document, either intentionally or inadvertently. Variables are well protected inside functions. It also means (whether an advantage or disadvantage) that you can use the same variable names both inside and outside a function and they still will be considered different variables. The function definition,

function Process ( Var_A )

and the function call,

Process ( Var_A )

both use a variable named Var_A (as an argument in the function and as a parameter in the function call). Nonetheless, these are considered as two different variables since Var_A of the function is local only to that function. Even though you can use the same variable names both inside and outside of functions, it's probably less confusing not to.

Any variables declared outside of functions are global; they are accessible by any of your scripts, inside or outside of functions. If you write a script such as

<SCRIPT>
var A = 10
var B = 15
var C = "Hello World"
</SCRIPT>

variables A, B, and C can be directly accessed and used by any other scripts scattered throughout your document. There will be scripting cases where you will want to make variables local, and other cases where they will need to be global. How you define them will depend on the scripting circumstances.

When to Use Functions

You can actually use functions for any and all script processing. However, there are a couple of situations where they seem to be called for:
  • Use a function when a script is used in more than one place in your document. Rather than repeating the code, change it into a function and call it whenever you need it.

  • Use a function when a script becomes "too long" to code in-line in an event handler. Rather than wrestle with alternating quotation marks, long single-line quotes, nested parentheses, and the like, put it all in a function and call it up.

This has been a brief introduction to functions. You will see and work with many more as you proceed through this tutorial and, hopefully, become well-acquainted with and preferential in their use.


Previous Contents Next