![]() |
![]() |
In javascript, you can define functions, which are statements that are used to carry out some task that you define. Functions are useful because they can be reused, meaning that they can be called as many times as you need them in the script.
You begin with the word function and then give it a name following javascript convention. Then you use parentheses, that, when reusing the function, will contain the name of the task.
The actual instructions that define the task are enclosed in curly braces.
This is an example of a script that defines and reuses a function three times. It is a two part script. The function is defined in the <head> of the document. In this example, message is the name for the data that will be passes when the function is called. Inside the curly braces, the alert objectis used to open a small alert window:
<script language=javascript type="text/javascript">
<!-- Hide script from older browsers
function saySomething(message) {
alert(message)
}
//End hiding script from older browsers-->
</script>
Here is the part of the script that goes in the body. It is used with three buttons and is repeated three times. Because the action will occur when the user clicks on the button, the onClick event handler is used.
Because buttons are being used, they must be enclosed in a set of non-functional form tags
Notice that only the data (the text of the alert window) changes:
<form>
<input type="button" value="First" onClick="saySomething('This is an example of a script')">
<p>
<input type="button" value="Second" onClick="saySomething('that can be reused because different')">
<p>
<input type="button" value="Third" onClick="saySomething('data is passed to the same function')">
</form>
And here's what it looks like:
Return to Javascript for home use.
| Page by Howard Rosenbaum | |
| Find me at hrosenba@indiana.edu | http://www.slis.indiana.edu/hrosenba/www/Demo/popup.html |