JavaScript: Functions, Status

S F S

 

Functions

Functions play a key role in most programming languages, and JavaScript is no different. A function can be thought of as a chunk of code that performs a specific task. Whenever you need the task to be done, you summon the function to do the task. For example, you could write a function that figures out today's date in mm/dd/yyyy format. You could write a function that combines a first name and a last name and prints the result to the screen using "alert()." It makes sense to write a function to do something that you may want to use more than once.

 

Example 1

Let's get introduced to the syntax of a function. Here is a script that uses a function that multiplies 2 numbers together and displays the result using "alert()":

<head>
<script language=JavaScript>

function mult(x, y)
{
var z;
z = x * y;
alert('The product of ' + x + ' and ' + y + ' is ' + z);
}

</script>
</HEAD>

<BODY>
<script language=JavaScript>
<!--

x = prompt("Please give me a number", " ");

y = prompt("Please give me a second number"," ");

mult(x, y);

//-->
</script>
</body>


CLICK to see this how this script behaves in a new window.

Note that the function is defined in the <HEAD> section, and that it begins and ends with curly braces. The function accepts 2 numbers ("x" and "y"), which are listed inside parentheses after the name of the function: "mult(x, y)." The function declares a variable "z," multiplies "x" and "y" together, and then assigns the result to "z." The results of the multiplication are then displayed using "alert()."

In the <BODY> section, values for "x" and "y" are obtained using "prompt()." The function "mult(x, y)" is then called and the variables "x" and "y" are sent to the function for it to use.

 

Status Bar

As noted in your terms sheet, the Status Bar in the browser window is just above the Start button. You can change the contents of the Status Bar by assigning text to "window.status" or often simply to "status." Following is an example that illustrates the use of prompt(), a function and a link to change the Status Bar.

 

Example 2

<head>
<script language=JavaScript>

function changeStatus(msg)
{
status = msg;
}

</script>
</HEAD>

<BODY>
<script language=JavaScript>
msg = prompt("What would you like to see in the Status Bar?", " ");
</script>

<center>
<a href="javascript:changeStatus(msg)">-- Change Status Bar --</a>
</center>

CLICKto see this how this code looks in a new window.
Note: This may not work in Navigator.

 

Other Resources

Try these links on Functions:


Page Link
Functions JavaScript Goodies
Functions WDVL
Functions WebTeacher

or check out one of our reference books, or look for other help on the Web.