In JavaScript functions should be written in the head
tags so that the function will be loaded when the browser loads. The
function then can be called from the body in of the script. Below I'll
Create some simple functions to get us started.
Here is a script where you enter your favorite football team. It uses a
function I called validateTeam(). There is a case structure inside the function
that displays an alert window that displays your favorite team name and opens a
new window that loads the url to the website of the team you enter. You
can find the code for the script below.
Here I have written a script that will display data in
an alert message box that pops us in a new window. There are 2 different
buttons and 2 different functions here. The first function is proverb1()
and is called in the body after a user clicks the "Computer Proverb 1
button". The same is true when the user chooses "Computer Proverb 2
button", the only difference is that a different proverb is displayed.
<html><head>
<title>Function Page</title>
<script type="text/javascript">
<!--
//Creating a few simple functions proverb1 and proverb 2
// Here is the first function
function proverb1()
{
alert("You can't teach a new mouse old clicks!")
}
//Here is the second function for the second proverb
function proverb2()
{
alert ("Don't byte off more than you can view")
}
//-->
</script></head><body>
<form name="proverbForm">
<!-- // the functions are called in the "onclick" events//-->
<input type ="button" value="Computer Proverb 1" onclick="proverb1()"
// Used for spacing of the
buttons.
</form>
<input type ="button" value="Computer Proverb 2" onclick="proverb2()"
</body>
Here are the buttons that the above script generates.
Try clicking on them to use the functions I've created to display alert
messages.
Now try creating a JavaScript with your own function!