Yet More JavaScript

Events and Writing Functions

You have seen some various pop-up boxes, the alert box and the confirm box. These boxes appear on screen even before the entire page loads in the browser window. Ideally, you would want to see these messages on the occurence of an event. The way to do this is to use functions. When we write functions, we can perform specific tasks only when we need these tasks be performed and not otherwise. Here's a sample code for all 3 types of pop-up boxes:

Pop up Boxes

<html>

<head>
<script>

    function alertSample()
    {
        alert("This is an alert box.");
    }

    function confirmSample()
    {
        if (confirm("If you are 18 or older press OK."))
	{
	    alert("confirm() returned TRUE.  You can view this page.");
	}
	else
	{
	    alert("confirm() returned FALSE.  You cannot view this page.");
	}
    }

    function promptSample()
    {
        your_name = prompt("This is a prompt box.  Now tell me your name.");
	if (your_name != "undefined")
	{
	    alert("You entered " + your_name + ".");
	}
	else
	{
	    alert("You didn't enter anything.");
	}
    }

</script>
</head>

<body>

<form name="javascriptform">
<input type="button" value="Alert" onClick="alertSample()">
<input type="button" value="Confirm" onClick="confirmSample()">
<input type="button" value="Prompt" onClick="promptSample()">
</form>

</body>

</html>
Try clicking on the button below and you will trigger an event.

Similarly, another function would cause another type of popup window to open. The following code is from above:

<form name="javascriptform">
...
<input type="button" value="Confirm" onClick="confirmSample()">
...
</form>
This creates the confirm button:
The value tag above with value="Prompt" and onClick="promptSample()" produces the following:

The syntax of a function in javascript is as follows:
function function_name(variable1, variable2,... variableN)
{
        function statements...
}

The open and closed curly brackets ({,}) mark the start and the end of the function.

Looping

There are two different kinds of loops: the 'for loop' and the 'while loop'.

For loop

The syntax of the 'for loop' is:

for( variable = initial_value; 
     variable conditional final_value; 
     variable operator increment/decrement_value )
{
        statements to be looped...
}
The Fibonacci #'s is the sum of numbers beginning with 1 up to some amount (n).
function factorial(n) {
    var sum = 0;
    if ( (n >= 1) && (n <= 100) ) { 
        for ( var i=1; i<=n; i+1 )
	{
	    sum = sum + i;
	}
	alert(n + "! = " + sum);
    }
    else
    {
        alert("Invalid Input");
    }
}
The following code is placed within the body tags.
Enter a number between 1 and 100:
<form name="sampleForm">
<input type="text" 
       size="5" 
       name="upTo">
<input type="button" 
       value="Calculate" 
       onClick="factorial(document.sampleForm.upTo.value)">
Enter a number between 1 and 100:

While loop

The syntax of the while loop is:

while (loop_variable relational_operator  terminating_value)
{
        statements to be looped...
}
The previous for loop could be replaced by the following while loop:
var i = 1;
while ( i <= n )
{
    sum = sum + i;
    ++i;
}
++i means "increment i". It is the same as i = i + 1

Arrays

Here's how we declare an array:
array_name = new Array;
array_name can be any variable name,

You can initialize the elements of an array to the value 0 as follows:

for (i = 0 ;i < 20; i++)
{
    array_name[i] = 0;
}
The HTML code displays a button labeled "Enter" and a text area. When the button is clicked (onClick) the JavaScript function displayArray() is called. A sample array is initialized and the contents of that array are displayed in the text area.
<html>
<head>
    <title>Arrays</title>
    <script language="javascript">
    function displayArray()
    {
        myArray = new Array;
	myArray[0] = "University";
	myArray[1] = "of";
	myArray[2] = "Iceland";
	for ( var i=0; i<myArray.length; ++i )
	{
	    document.myForm.textFour.value = document.myForm.textFour.value + " " + myArray[i];
	}
    }
    </script>
</head>
<body>
    <form name="myForm">
        <p>
	<input type="button" 
	          value="Enter" 
		  name="enter"
		  onClick="displayArray();">
	<p>
	Result:
	<input type="text" 
	          size="40" 
		  name="textFour">
    </form>
</body>
</html>
Check it out
All arrays in JavaScript are objects. One property of any Array object is the length. Since there are 3 entries in myArray in the example above, myArray.length = 3.

Cookies

Cookies are used by web pages to help get and store data on the client side. They are taken care of by the browsers in name/value pairs.

When the following html is loaded into a web browser, a cookie set for the corresponding site with name="Cookie" and value="Monster!!!":

<html>

<head>
<script>
    function setCookie () 
    {
        document.cookie="Cookie=Monster!!!";
    }
</script>
</head>

<body onLoad="setCookie()">
Cookie Monster
</body>

</html>
Set the cookie
The following HTML can then read the cookie:

<html>

<head>
<script>
    function readCookie () {
       if ( document.cookie.length < 1 ) {
           document.write('No cookie set for this site.');
       }else {
           document.write('Cookie for this site: ' + document.cookie);
       }
    }
</script>
</head>

<body onLoad="setCookie()">
Cookie Monster
</body>

</html>
Read the cookie
For this site, depending on the browser you are using, the cookie will be stored with the following information:
Name:Cookie
Value:Monster!!!
Host:penguin.wpi.edu:4546
Path:/course/087254/lab1
Server Secure:no
Expires:at end of session