Computer Science Society Logo

JavaScript Tutorial

CLICK! JavaScript Evaluator


JavaScript is not Java, but does have many syntactical similarities. JavaScript utilizes an object oriented approach to programming. The language itself very closely resembles Java; however, it is not as sophisticated.

Let's take an informative look at a simple script:

<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script language="JavaScript">
var inputNum;
inputNum = prompt("How old are you?", "Enter Your Age");
window.document.writeln("Hello World I am " + inputNum);
</script>
</body>
</html>

Lets take the script line by line:

<script language="JavaScript">
We must let the browser know that we are going to be using some sort of script and we specify the script with the language argument. In Netscape and IE the default scripting language isJavaScript so you would need only the <script> tag; hoever,it is recommended for clarity to include the language attribute.

var inputNum;
Declares a variable called inputNum. In JavaScript variables neednot be declared; however, it is highly recommended for clarity. Alsovariable types are deciphered by the interpreter, you do not specifytypes.

Note: a declared variable is declared only within the scope of thedeclaration, an undeclared variable is assumed global. Beware ofglobal variables, they will make function writing tasks difficult.

inputNum = prompt("How old are you?", "Enter Your Age");
Here we set our variable = to the user input from a prompt command. A prompt command prompts the user with the first string, and sets the default answer to the second string.

window.document.writeln("<STRONG>Hello World I am " + inputNum + "</STRONG>");
Let's take our time with this one. The obvious answer: we write "Hello World I am #" to the screen, # being the user's input from our previous prompt statement. Not so obvious answer: we access our window object (the browser at our domain), then we call the document object within the window object, and we employ the write method within the document object.
The interpreter knows to convert inputNum to a string instead oftrying to add a string and a number numerically because there isa string in the addition sequence. If I were to change the statementto window.document.write(inputNum + 5); the interpreter would add 5to the user input and display that to the screen.
The next important point is that our document.write method writes to theHTML interpreter on our browser, not directly to the screen. So this meansthat the rules of HTML apply within our string to be passed to the writemethod. We can include tags.

</script>
Simply tells the browser that we are done with our script.

Note: The <script> tag must be within the body of our HTML.

Warning: When using javascript you must keep in mind that not all browsers have all methods implemented in their JavaScript interpreter. In fact, a user may have a browser that doesn't even recognize JavaScript. If a user's browser doesn't recognize code, it assumes that it is text and displays it to the screen. Let's make sure our javascript isn't outputted as text to the screen for our non-javascript users.

<script language="javascript">
<!--
.
.
.
//-->
</script>

The tags appearing after our opening script tag and before our ending script tag are comment tags. Older browsers that do not recognize JavaScript recognize the comment tags as commenting out the whole block of code, whereas javascript enabled browsers have new rules for comments, where only the line is commented. Notice how I comment out the --> tag with the JavaScript line comment method //. This ensures that if I do have a JavaScript enabled browser that the JavaScript interpreter will ignore the --> line.

Let's talk about images within HTML and JavaScript. When we attach an image to our web page the browser loads that image into an array called images[]. Each image is associated with a specific area of the browser window where we declare <img src="blah.gif">. If this was our first image declaration than document.all.images[0].src would equal "blah.gif". This could help in the future but even more helpful is our ability to name images.

<img src="blah.gif" name="image_one">
<img src="blah2.gif" name="image_two">

<script language="JavaScript">
window.document.image_one.src=image_two.src;
</script>

We have now replaced our first image with our second. image_one is the name associated with our object of the image class. .src is the method which specifies the image name.

We can preload images into variables even before displaying them.

<script language="javascript">
var image_one=new Image();
image_one.src = "blah.gif";
</script>

This eliminates the problem of lengthly image downloads during
image swapping.

We can use the DHTML event model within JavaScript in order to create event responses. The text within quotes after an event trigger is always JavaScript.

<a href="#"
onMouseOver="window.document.image_one.src='blah2.gif';"
onMouseOut="window.document.image_one.src='blah1.gif';"
onClick="return false;">
<img src="blah.gif" name="image_one">
</a>

This is an image swap. we add the onlick return false to show that nothing is done on a click. It need not be defined normally unless it is to be used.

Let's address our browser incompatability problem once again. Netscape 2.0 and MSIE 3.0 and below are not capable of performing our image swapping code. We can prompt our client's browser for name and version using navigator.appName, and navigator.appVersion But unfortunately the appVersion method returns a whole bunch of garbage along with the version number. In the image swapping case we can check if window.document.images returns true, and if so than the browser is swap capable.

<script language="javascript">
if (window.document.images)
{
//We're o.k.
}
else
{
//Don't do the swap.
}
</script>

<html>
<head>
<title>Forms with JavaScript</title>
</head>
<body>

<form name="Form1">
<input type="text" name="textBox1">
<input type="button" value="Go<" onClick="go();">
</form>

<script language="javascript>
function go()
{
var tval = this.Form1.textBox1.value;
}
</script>

It is important to note how we declare functions in JavaScript. We do not specify a return type. Also note that if I were to pass a variable into the function it would be within the parenthases.

We've created a form and stored the input into a variable. Notice that we can name our fields in the <form> tag. When we begin our javascript we can access the form fields through this name. By the way the "this" keyword returns the address of the current object, which in this case would be window.document, but only works within MSIE.

Let's take a look at return values of functions and passing
variables.

<script language="JavaScript">

var b = 5;

var squareB;

squareB = square(b);


function square(a)
{
return a * a;
}

</script>

Notice that we also do not specify types nor do we include the var keyword within the argument list of our function. Also, variables are passed by value unless they are objects or arrays which are passed by reference.

Arrays in JavaScript are declared as objects.

var c = new Array( 5 );

Allocates 5 spaces in memory and returns the address of the first space to the variable c. This address cannot be extrapolated because pointers are not specifically implimented within JavaScript, although c is technically a pointer, as are all variables.

c = [1, 5, 4, 77, 3];

Assigns the array 1, 5, 4, 77, 3 to the array within c. If we
want to traverse the array we need only do the following:

var j;
for (j = 0; j < c.length; ++j)
{
c[j];
}

Arrays have a length attribute which is public.
If we want to output an array we do not need to traverse the array.

document.writeln(c);

We can also declare multidimensional arrays:

var j;
var l = new Array(3);
for (j = 0; j < l.length; ++j)
l[j] = new Array( 3 );

This declares a 3 x 3 array. We can access the indeces like so:

l[1][0];

Which return the value within row 1 column 0.

Copyright 2002 Northeastern Illinois University.
Design and content by Kevin L. Stern
All Rights Reserved.
Material on this page may be reprinted for educational, non-commercial purposes
as long as Northeastern Illinois University is informed of such usage, all
material with an author listed is the intellectual property of that author
and may not be reproduced without permission.