JavaScript Basics- The Function
Author: Mick
White
Author's Site:MickWeb.com
Reference ID: 15628
The Terminology
A javascript function allows you to define a set of instructions
to the browser, you can instruct the browser to "run"
the script as a result of an "event" such as "onclick"
or "onmouseover", or to run automatically. A javascript
function will be in the format as shown below:
<script language="JavaScript"> <!-- function function_name([parameter(s)]){ statements; } // --> </script>
For a real world example consider the following javascript:
<script language="JavaScript"> <!-- function my_alert(){ alert("Hello world."); } // --> </script>
To call or "invoke" (run) this function you could use
the "onclick" handler of the <a> tag, as follows:
<a href="javascript:void(0)" onclick="my_alert()">Try it</a>
Or you could place the following anywhere on your page, whereby
the script will run as soon as the browser sees it. The function
must be defined "before" it is invoked, however.
<script language="JavaScript"> <!-- my_alert (); // --> </script
Function parameters or "arguments"
A function can be passed any number of arguments. Each argument
is separated by a comma:
function my_function(argument1,argument2,...argumentn){ statements that use the arguments; }
The following script example is passed a form text entry as an
argument.
function my_alert(msg){ alert(msg);
<a href = "javascript:my_alert(document.form1.entry.value)">Try it</a>
Notice how we refer to the form text entry.
document.form_name.textfield_name.value
This is an example of how javascript refers to "objects",
a very important concept in javascript.
|