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 LocationsThe 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> 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 HandlersMost 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.
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 ScriptsEvent 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>
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>
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 FunctionsA 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>
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>
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 SyntaxThe general format for the scripting of a function is
function FunctionName ( ) 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 FunctionsThe 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>
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.
|