You are on page 1of 38

1.

Introduction

Javascript is a compact, object-based scripting language. It can provide


interactive web pages, validate form data, and make your web page
clearer.

Writing JavaScript
The JavaScript code is embeded into the HTML document. Simply place
the JavaScript statements within the SCRIPT tag.
<SCRIPT>
JavaScript code goes here...
</SCRIPT>

You can optionally specify the LANGUAGE attribute in the SCRIPT


tag.
<SCRIPT LANGUAGE="JavaScript">
JavaScript code goes here...
</SCRIPT>

For older browsers which do not understand JavaScript, you need to hide
the script with the comment tags.
<SCRIPT LANGUAGE="JavaScript">
<!-- hide JavaScript from older browsers
JavaScript code goes here...
// end hiding from older browsers -->
</SCRIPT>

If you wish to define functions, they should be defined in the HEAD


part of the HTML document. This is because the HEAD is the first part
of the document which is loaded, and that ensures that your functions
will be available for your JavaScript code.
A complete HTML example document:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide JavaScript from older browsers
function bar() {
document.write("Hi there.")
}
// end hiding from older browsers -->
</SCRIPT>
</HEAD>

<BODY>
HTML document goes here...
</BODY>
</HTML>

And last, but certainly not least, you may put JavaScript statements
within HTML tags. For example, an event handler is placed directly in
the tag:
<input type="button" onClick="foo()">

If you don't understand what the onClick event is, don't worry. We'll be
getting to that later. You can also place it on the right side of a
name/value pair. For example:
<input type="text" value="compute_value()">

In this example, the value returned by the function compute_value is


returned and is used for the value of the INPUT tag.
2. Basic Data Structures & Stuff

Variables
 Variable Types
So... You're asking yourself what types of variables does Javascript
allow?
Okay so maybe you're not thinking it, but let's pretend.

Numbers (e.g. 123 321 132 231 312 etc...)


(e.g. true false)
Logical Values
No fuzzy logic yet...
Strings (e.g. "Hello World", "I love Javascript!")
(e.g. null)
Null
What you wanted more?!

 Variable Names
So.. Now that we know what type variables you can have, is there a
limitation on what we can call the variable? But of course. In order for
Javascript not to throw a weird error out on execution, you must use
variable names that begin with a letter or underscore ("_"); numbers
just don't cut it! This is mainly because if you start to use numbers,
Javascript will assume that the rest of your "word" is a number. The only
letters you can use are "A" through "Z" (upper & lower case). No funky
high ascii or spaces, please. Oh, by the way, Javascript is case-sensitive
so Coolvariable1 is not the same as CoolVariable1 [Note the
capitalized "V"].
 Variable Values
Although explanation of variable values are not need, some attention
must be given to strings. The main problem occurs when you are
programming away and all of a sudden you need to use a quote within
your string. What can one do?! Well, think of another method of doing
what you want without using quotes, or take the lazy man's method and
"escape the quotes" with your friend and mine, the backslash ("\").
ex: "this is a string value with \"quoted\"
material in it"

In addition, you can aslo use other commonly escaped unix-type stuff
like:

\b Backspace
\f Form feeds
\n New line
\r Carriage return
\t Tab
 Variable Syntax
[var](variable name) = (variable value);

A few notes:

 The "var" is optional but should be used for good style


 The ( )'s are not typed in.
 Variables can be assigned to other variables.

Here are a few examples:


var thisvariable = false;
var thatvariable = 1;
var thosevariables = "two";
var novariables = null;

 Arrays
Arrays are variables that can hold a lot of different values. You can use
brackets to specify which element in the array you wish to reference.
Example:
student[0]="George";
student[1]="Jane";
student[2]="Elroy";
student[3]="Astro";
student[4]="Judy";
This creates five elements in the array and sets their values. Pretty
simple, eh? You can do a lot with arrays. We'll get back to them when
we talk about objects.

 Expressions
So.. Now that you have all these great variables, let's do stuff with them!
But as with anything, we'll have to start from the beginning.

 Operations
Here's a quick review of the operators that you probably know (from
previous programming experience, looking else where in this manual,
and/or knowing math.) Oh forget it! Basically if you don't know what
"=", "+", "-", "*", and "/" mean, Javascript is above your head.
Otherwise let's go on to the important operators that aren't so obvious.

Basically if (Condition) is true, the


(Condition) ? Variable1 : expression
Variable2 has the value of variable1, otherwise it's
variable2.
Same as: Variable1 = Variable1 +
Variable1 += Variable2
Variable2
Same as: Variable1 = Variable1 -
Variable2 -= Variable2
Variable2
Same as: Variable1 = Variable1 *
Variable1 *= Variable2
Variable2
Variable1 /= Variable2 Same as: Variable1 = Variable1 /
Variable2
Variable++ Same as: Variable = Variable + 1
Variable-- Same as: Variable = Variable - 1

 Conditional Stuff
Variable1 == Variable2 Variable1 is the same as Variable2
Variable1 > Variable2 Variable1 is greater than Variable2
Variable1 >= Variable2 Variable1 is greater than or equal to Variable2
Variable1 < Variable2 Variable1 is less than Variable2
Variable1 <= Variable2 Variable1 is less than or equal to Variable2
Variable1 != Variable2 Variable1 is not equal to Variable2

One quick note on String operators. If you want to merge two strings,
just add them in order as if they were numbers. (When you add strings,
you get the sum(concatination) of the strings). Example:
"This is a " + " string in " + " multiple
parts."

Functions
Functions are basically ways of executing many lines of codes with in
one line (or less); like a mini-program. Let's say for example you have to
constantly do something like this:
if(confirm("Is this the correct value?")) {
top.frame1.document.open();
top.frame1.document.write("You chose
wisely...");
top.frame1.document.close();
}

Don't worry about understanding what this does. We're just using it for
an example.

So, instead you can create a function where you can pass it some values.
Below you will the syntax of a function:
function function_name(parameter_1,
parameter_2, ... parameter_n){
line_1;
line_2;
.
.
.
line_n;
}

So, whenever this function is called it will execute the lines of code
between the { }'s. Here is an example of using a function for the above
example:
function Iamlazy (output_string){
if(confirm("Is this the correct value?")) {
top.frame1.document.open();
top.frame1.document.write(output_string);
top.frame1.document.close();
}
}
Functions are executed when someone makes a reference to them by
calling their name followed by their parameters in parentheses. For the
above example you would reference it with the following:
Iamlazy("You chose wisely...");

With functions, they give you increased power, so you can output
anything you want. As in:
Iamlazy("You chose poorly...");

So you can define the function once, and call it many times with any
different value you wish.

Don't forget that you should put functions into the <HEAD> part of the
document so that they are loaded first.

You may notice that there is no type-checking. That's because JavaScript


is a very loose language. You never have to specify what type of
variable something is. This can be a blessing or a curse.

 Returning Values
Your function can return a value. Just use the return statement.
return(some_value);

Note that the function exits as soon as it hits the return statement.

Conditional Statements
There is basically one type of conditional statement, the if statement.
The syntax is as follows:
if (condition) {
statement1;
statement2;
.
statementN;
}
[else {
statement1;
statement2;
.
statementN;
}]

Example:
if (variable == 1){
DieChemistryDie();
}
else {
Javascript = "Cool!";
}

Basically it reads like English, "If the condition is true, execute the
statements below [else execute these statements]." Note, the else part is
optional.

 Loops and whatnot....


In Javascript there are two basic types of loops that anyone cares about;
for loops, and while loops. The syntax for each follows below:

for ("variable initialization";"condition to


exit loop";"variable increment expression";){
statement1;
statement2;
.
statementN;
}
This should be pretty self-evident in how. If you're still confused, look at
this example. It should clear it up.
for (var i = 1; i <= 10; i++){ variable1++ }
This example basically adds a number to itself 10 times. On to the
while loop!!
while (condition){
statement1;
statement2;
.
statementN;
}
This is probably the easiest of the loops.
Basically while the condition
is true it will execute the lines in the { }'s.
Easy? Thought you would
think so. Now here comes the more complicated
stuff. What if you want to
break out of a loop prematurely? Well guess what
command you use? BREAK!
Here's an example:

function testBreak(x){
var i = 0;
while (i <6) { if (i="=" 3) break; i++; }
return i*x; }
The previous example basically terminates the while loop when i is 3,
and then returns the value of 3 * x. Now what happens if you want to
skip the rest of the loop; use continue ! Here an example with
continue being used:
i = 0;
n = 0;
while (i <5) { i++; if (i="=" 3) continue; n
+="i;" }
When the while loop is executing, when i equals 3, it will skip the line n
+= i; and continue on with the while loop. All other times it executes
like normal.

There is one quick note that you might have noticed. If you have only
one statement, you don't need the curly braces,{ }'s. While I'm on
technicalities, I might as well mention that you don't need semicolons at
the end of statements. The Javascript interpreter in will decide when a
statement is complete. Granted it usually easier to see code with explicit
endings of statements though.

 Comments

Just a quick note on comments. They look just


like C++ comments (Gee, kinda
like the rest of JavaScript?)...

For a single line comment, use:


// Every good boy and girl comments their code
For multi-line comments:
/* This comment spans
several lines... */

Objects
What's an object you say? Well, think of it as a variable with
subvariables. Here's a quasi-diagramatic explaination:

.--- Subvariable3
|
Variable-+--- Subvariable2
|
`--- Subvariable1
The actual syntax of accessing an object's subvariables is very much
similar to that of accessing a variable; the main difference is a dot. ex:
variable.subvariable

So let's say we had a variable that was nothing but a collection of


smaller variables. For example: Our variable was "Dog" and our
subvariables were "Number_of_Tails", "Number_of_Arms",
"Number_of_Legs" & "Number_of_Eyes". To use these subvariables
you would access Dog.Number_of_Tails ,
Dog.Number_of_Arms , Dog.Number_of_Legs &
Dog.Number_of_Eyes.

For example:
Dog.Number_of_Tails = 1;
Dog.Number_of_Arms = 0;
Dog.Number_of_Legs = 4;
Dog.Number_of_Eyes = 2;

So, how about we create some objects in Javascript? There are a variety
of ways to create objects. One way is to just start using them. In the
above example when we defined the properties of Dog (tails, arms, etc.)
we created an object. Wow, that was easy. However, there's a better way
to do it. Let's define an object with a function using the new syntax.

function animal
(Num_Tails,Num_Arms,Num_Legs,Num_Eyes){
this.Number_of_Tails = Num_Tails;
this.Number_of_Arms = Num_Arms;
this.Number_of_Legs = Num_Legs;
this.Number_of_Eyes = Num_Eyes;
}

var Dog = new animal(1,0,4,2);


At this point you should be scratching your head and saying, "Huh?
What's this this thing and this new thing?!" Fear not, all will be
explained (I hope).

this is a special word in Javascript that refers to the object you are
creating/talking about.
new is used when creating a new object.

Basically when you create the object via the line var Dog = new
animal(1,0,4,2); you are assigning the word Dog to this.
So... Why use this long method of doing what we did in 4 lines located
above in the begin of this section? Well what if you had to do a lot of
different animals like Birds, Monkeys, Fish, and Cockroaches? With out
current setup, you would just have to type in:
var Bird = new animal(1,0,2,2);
var Monkey = new animal(1,2,2,2);
var Fish = new animal(1,0,0,2);
var Cockroach = new animal(0,0,6,2);

instead of typing in 16 lines!! And if you use the object "animal" over
and over again you will notice basically a (n x 100%) reduction in code
where n is the number of subvariables. But I digress.... In a phrase,
"Objects Rock!"

 Methods
But it doesn't stop there! Not only can an object have a lot of different
properties (variables), they can also have methods. A method is simply a
function within an object. So not only can we access a property of an
object like:
Dog.Number_of_Tails=1;

We can also access a method (function) of an object.


Dog.bark();

This causes the Dog object to bark. A method is an action. It causes the
object to do something. So how do you define a method. Use the
following syntax:
object_name.method_name = function_name

So, after you have defined some function, you can assign it to the object.
Nothing explains better than an example, so let's make a really big
example of our animal object.
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide JavaScript from older browsers
function squeal (string) {
//Outputs some sort of speech
document.write(string);
}

function grow (property_name) {


//Makes some part of the object grow
this[property_name]++;
}

function print_properties() {
//prints the properties of an object
for(var property_name in this) {
document.write(property_name + "=" +
this[property_name] + "<br>");
}
}

function animal
(Num_Tails,Num_Arms,Num_Legs,Num_Eyes){
//creates a new animal object
//initialize properties
this.Number_of_Tails = Num_Tails;
this.Number_of_Arms = Num_Arms;
this.Number_of_Legs = Num_Legs;
this.Number_of_Eyes = Num_Eyes;
//define the methods
this.squeal = squeal;
this.grow = grow;
this.print_properties =
print_properties;
}

// end hiding from older browsers -->


</SCRIPT>
</head>
<body>

Creating the new object.<br>

<SCRIPT LANGUAGE="JavaScript">
<!-- hide JavaScript from older browsers

//Create a new object


var Dog = new animal(1,0,4,2);

//Make the dog bark


Dog.squeal("Ruff!<br>");

//Make the dog grow a new tail


Dog.grow("Number_of_Tails");

//Display the dog's properties


Dog.print_properties();
// end hiding from older browsers -->
</SCRIPT>
</body>
</html>

OK. I hope you noticed that I popped a few new things about objects on
ya, so lemme explain them. In the past we have referenced property
names with the period notation like Dog.Number_of_Tails. There
is another way to reference a property name with brackets. It looks like:
Dog["Number_of_Tails"]. That's it. Just use a string as the name
of the property.

That's the first thing I popped on you. Next, in the


print_properties method, I used the following code:

for(var property_name in this) {


document.write(property_name + "=" +
this[property_name] + "<br>");
}

First, the document.write() method just prints text. We'll talk


more about that later. Just take that for granted for now.

This is called a for..in statement. The for..in statment cycles through the
property names in an object. That's it. The format is:
for (some_variable in object_name) {
statements
}

It takes a variable (in this case it is property_name), and makes it


equal to the name of the first property in the object (in this case it is
Number_of_Tails). Then it goes on to the next property. It
continues doing this until it has gone through all of the properties. Note
that this includes both variables and methods.
There's another thing that I haven't shown yet. It's the with statement.
Sometimes you might be working with a single object (such as Dog),
and you might get tired of typing Dog a lot. Here comes the with
statement to the rescue! You can set the Dog object as the default object.
The syntax is:

with (object_name) {
statements
}

This makes all the statments in the curly braces {} assume you are
talking about the given object. So for example, if we had:
Dog.Number_of_Tails=3;
Dog.Number_of_Arms=2;
Dog.Number_of_Legs=Dog.Number_of_Arms*3;
Dog.Number_of_Eyes=Dog.Number_of_Tails*5;

This can be simplified with:


with (Dog) {
Number_of_Tails=3;
Number_of_Arms=2;
Number_of_Legs=Number_of_Arms*3;
Number_of_Eyes=Number_of_Tails*5;
}

Whew.... I hope you made it through all that. Don't worry if you didn't
get it all the first time through. You'll learn through experience. Just
remember that you can come back here to see how it's done.
3. HTML Manipulation

JavaScript's main power resides in the fact that it can output to your
HTML document. In fact, that's its only power! Actually, it can do some
other things, but we'll get into that later.

Document Output
Outputting to the current document is easy. Just use the methods write
and writeln. Example:
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide JavaScript from older browsers
document.write(" This <a
href=\"index.html\">link</a> was produced by
JavaScript")
// end hiding from older browsers -->
</SCRIPT>

JavaScript is interpreted in real time. This means that any HTML


appearing before this JavaScript code will appear first. Then the
JavaScript code will be ran and the resulting string will be placed. Then
any HTML after that will be displayed.

The method writeln is the same as write but a new line (carriage return,
return character, whatever) will be placed at the end of the line.

If you have multiple frames or windows, you can "talk" to those other
windows or frames. Just use the proper referencing. For instance, if we
have two frames, one called frame1 and the other called frame2, you
can send data between the two. If we have our JavaScript code in
frame1 and wish to send something to frame2, then the following code
will do the trick:
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide JavaScript from older browsers
top.frame2.document.open();
top.frame2.document.write("Hi there");
top.frame2.document.close();
// end hiding from older browsers -->
</SCRIPT>

top specifies the top of the document heirarchy. The next argument is
the name of the frame. After that you can specify any object within the
frame. In this example, we use the document object. And finally we use
the write method of the document object.

You may have noticed the open() and close() methods. These calls open
a stream from one object to another. In other words you need to open the
door to other objects before you can start talking to them. Just be sure to
close the door when you're done. One sidenote regarding open() is that it
will clear the target window. Don't forget that.

There are some other features for open(). open() by itself implies that
you are opening a text/html document. This means you can only send
over plain text (or HTML). If you wish to send something else, then you
can specify that MIME Type. Some MIME types are image/gif, or
image/jpeg. So if you open it with a gif type, then it will expect you
to send a GIF image. Example:
document.open("image/gif");

For more information, check out a handy reference.

If you wish to change the URL location of another window (or the
current window for that matter), you can use the location property of the
document object. Example:
document.location="http://www.yahoo.com/";
If you wish to load a document in a specific frame, just reference it
appropriately.

Opening Windows and Frames

Opening a new window is easy. Use the open() method. However, this
isn't the same open() method we used for streams. This open method
takes two or three variables. The syntax is:
[window_var=] [window].open("URL","window_name",
["window_features"])

The items in brackets are optional.

This first variable is the URL. Just give it a URL string. Pretty easy.
Next comes the name of the window. This is a unique identifier of the
name of the window. If you specify the name of a window that does not
exist, one will be created. If you specify one that does exist, then the
URL is sent to that window.

The last part is optional. Here you can specify some special attributes for
the window. If you don't specify any attributes, then the window looks
like a normal web browser. However, you can set several features of it
explicitly. You can change such things as the size, whether or not there
is a menubar, etc.

Example:
<SCRIPT LANGUAGE="JavaScript">

my_new_window=window.open("","","menubar=no");
my_new_window.document.write("This is a new
window.");
my_new_window.document.close();
</SCRIPT>
This will pop up a new web browser without a menubar and print some
text to it.

The window_features command can take several options.


 toolbar[=yes|no][=1|0]
 location[=yes|no][=1|0]
 directories[=yes|no][=1|0]
 status[=yes|no][=1|0]
 menubar[=yes|no][=1|0]
 scrollbars[=yes|no][=1|0]
 resizable[=yes|no][=1|0]
 width=pixels
 height=pixels

To specify multiple options, seperate them by commas. The boolean


value on the right side can be specified in several ways. The following
examples have the exact same effect:
toolbar=yes
toolbar=1
toolbar

As you can see, giving no boolean value is the same as yes.

If you wish to close a window, use the close() method. In our previous
example, we opened a window called my_new_window. If we wish to
close it, use:
my_new_window.close();

Pretty simple, eh? If you wish to close the current window, you can use
either:
window.close();
or
self.close();

Frames
To create some frames, you need to first create a window. Once you
have done that, you need to send the appropriate HTML to that window
to create the frames. It'll look a little like this:
some_new_window=open("","");

some_new_window.document.write("<html><frameset
cols=\"*,*\">>\n",

"<frame src=\"frame1.html\" name=\"frame1\">\n",

"<frame src=\"frame2.html\" name=\"frame2\">\n",

"</frameset></html>");
some_new_window.document.close();

Now, if you wish to send data to the appropriate frame, you can do:
some_new_window.frame1.document.open();
some_new_window.frame1.document.write("I am
now writing in frame1.");
some_new_window.frame1.document.close();

If you wish to close the two frames you just created, you can just write
to the parent document. When you call the open() method, this will clear
the parent window and remove the <frameset> tags. The result is that
your frames will be clobbered. Example:
some_new_window.document.open();
some_new_window.document.write("This is a new
document without frames");
some_new_window.document.close();

The above code just cleared the window (when we called open()) and
wrote some text to it, thus removing the frames.

Dialog and Alert Boxes


Dialog and alert boxes are usefull for a variety of purposes. You can use
them to get input from the user. You can also use it for debuging
purposes.

First, the alert box. The alert box pops up in the middle of the screen
with some text. It gives the user an OK box. Example:
alert("That is an invalid value.");

That's it.

The next item is the confirm dialog box. The confirm dialog box is the
same as the alert except that it gives an OK and Cancel buttons. Then, it
returns true or false corresponding to OK or Cancel respectively.
Example:
if(confirm("Would you like to try again?")) {
document.location="index.html";
}
else {
quit();
}

The final type of dialog box is the prompt dialog box. The prompt
dialog box is the same as the confirm dialog box, but the user can input
some data. The prompt() command then returns the value that the user
entered. You can optionally specify the default value. The format is:
prompt(message [, default_value] )

Example:
username=prompt("Please enter your name.","");

Another example:
the_value=prompt("Please enter the amount you
wish to bet.",0);

It is always recommended that you give it a default value. If you do not


specify a default value, then the string "undefined" is placed in the input
box which looks really bad.

Event Handling
Event handling is one of the most important aspects of JavaScript. It
allows your JavaScript code to respond to certain events. This includes
when the user clicks the mouse, or changes a value, or moves the mouse.

Let's first take an overview of all the different events.

 onBlur
 onChange
 onClick
 onFocus
 onLoad
 onMouseOver
 onSelect
 onSubmit
 onUnload
Whew... For a simple scripting language, that sure is a plethora of
events.

Each event works a little differently. Each one is intended for different
parts of the document. For instance, the onBlur event is used with a
select, test, or textarea fields on a form. It can only work on these
things. So for instance:
<input type="text"
onBlur="some_javascript_function()">

Just stick the event in the tag, and give it some JavaScript code to run.

Since all the events work a little differently, let's just look at them in
turn.

 onBlur
The onBlur event occurs whenever a form object loses focus.

Tags it works with:


 <input type=text>
 <input type=textarea>
 <select>

Example:
<input type="text" onBlur="save_value()">

 onChange
The onChange event occurs whenever a form object loses focus AND
its value has been changed.
Tags it works with:
 <input type=text>
 <input type=textarea>
 <select>

 onClick
The onClick event occurs whenever a form object is clicked with a
mouse.

Tags it works with:


 <input type=button>
 <input type=checkbox>
 <input type=radio>
 <input type=reset>
 <input type=submit>
 <a href="">

 onFocus

The onFocus event occurs whenever a form object receives focus either
by the keyboard or the mouse. If the user uses the mouse to select text
(by dragging the mouse), this does NOT general an onFocus event.
Instead, it generates an onSelect event.

Tags it works with:


 <select>
 <input type=text>
 <input type=textarea>
 onLoad

The onLoad event occurs whenever the browser is done loading the
window. If there are frames within the window, then it waits until all the
frames are loaded.

Tags it works with:


 <frameset>
 <body>

 onMouseOver
The onMouseOver event occurs whenever the mouse pointer goes over
an object from outside that object. Be sure to return true; at the
end of your statement.

Tags it works with:


 <a href="">

Example:
<a href="http://www.acm.uiuc.edu/"
onMouseOver="window.status='ACM'; return true">

The above code will change the status bar to say "ACM" whenever the
mouse runs over the link.

 onSelect
The onSelect event occurs whenever the user selects some text within a
text or textarea field.

Tags it works with:


 <input type=text>
 <input type=textarea>

 onSubmit
The onSubmit event occurs whenever a form is submited. To prevent
the form from being submited, use return false to stop it. Otherwise use
return true to make the form be submitted.

Tags it works with:


 <form>

 onUnload
The onUnload event occurs whenever the user leaves a document.

Tagis it works with:


 <frameset>
 <body>
4. MultiMedia

Now's your chance to do some spicey effects with JavaScript. Don't


overdo it with this stuff since JavaScript is a little slow. However, you
can add a little more functionality to your web page when you take
advantage of this stuff.

Images
In Navigator 3.0, the kind folks at Netscape added the Image object.
There are a variety of ways to use this object. One way is to use the
image constructor Image([width,height]). This will allow you
to create a new image object. What do you do with an image object?
Well you can load an image into it while the page loads to ensure that
the image will be loaded from the cache for speedy access. An image
object has the following properties:

 border - The size of the border around the image.


 complete - Boolean value reflecting whether or not the image has
completed loading.
 height - The height of the image.
 hspace - The amount of horizontal spacing.
 lowsrc - The URL of the low resolution version of the image.
 name - The name of the image.
 prototype - Allows you to add more properties to the image.
 src - The URL of the image.
 vspace - The amount of vertical spacing.
 width - The width of the image.

So, to create a new image object, you can do the following:


some_image = new Image(100,200);
some_image.src = "spaceboy.gif";
This will create a new image that is 100x200 in size (if the actuall image
is a different size, then it is scaled to 100x200).

Once your document has been loaded, you can not add any more images
to be displayed. However, you can change which ones that are currently
displayed. There are two ways to do this. The first way is to reference
the image specifically through the document object. This can be done as
follows.
<img name="disarm" src="disarm.gif" height=100
width=200>

<script language="JavaScript>
document.disarm.src="today.gif";
</script>

This will change the current image of disarm.gif to today.gif. The other
way to change the image is to use the images array. The images array is
a property of the document object. The first item in the array is the first
image on the document. So, to do the above example using the images
array, it would look like this:
<img name="disarm" src="disarm.gif" height=100
width=200>

<script language="JavaScript>
document.images[0].src="today.gif";
</script>

So here's an example where we first pre-load a few images into the


cache. A blank image is first displayed. Then, the user can select which
image is displayed with a select box.

<html>
<head>
<script language="JavaScript">
function init() {
// loads the images into the cache for
speedy access
cd_cover = new Array();
for( i=0; i<5; i++) { cd_cover[i]="new"
Image();
cd_cover[i].src="/destination65673/18222/cd" + i
+ ".gif"; } } function change_picture(x) { //
changes the current picture
document.cd_image.src="/destination65673/18222/c
d_cover[x].src;" } </script> </head> <body
onLoad="init()" > <img name="cd_image"
src="http://www.ukcomputers.com/nclcs/JavaScript
/blank.gif" > <form> <select
onChange="change_picture(this.options[this.selec
tedIndex].value)" > <option value="0" > The
Weasels <option value="1" > Rock Hill Pilots
<option value="2" > Gold Finger Crush <option
value="3" > Killer Tomatoes <option value="4" >
Evangelica </select> </form> </body> </html>

Animation

To animate using these methods, you just need to


cycle through the images in a single location.
Note
that this example was blatently stolen from
Netscape...At least I changed it a little
bit..Oh well.
<script language="JavaScript">
delay = 100
imageNum = 1
// Preload animation images
theImages = new Array()
for(i = 1; i <11; i++) { theImages[i]="new"
Image()
theImages[i].src="/destination65673/18222/some_i
mage" + i + ".gif" } function animate() {
document.animation.src="/destination65673/18222/
theimages[imagenum].src" imageNum++ if(imageNum>
10) {
imageNum = 1
}
}

function slower() {
delay+=10
if(delay > 4000) delay = 4000
}

function faster() {
delay-=10
if(delay <0) delay="0" } </script> <BODY>
<IMG NAME="animation"
src="http://www.ukcomputers.com/nclcs/JavaScript
/some_image1.gif" ALT="[Animation]"
onLoad="setTimeout('animate()', delay)" > <FORM>
<INPUT TYPE="button" Value="Slower"
onClick="slower()" > <INPUT TYPE="button"
Value="Faster" onClick="faster()" > </FORM>
5. Cookies

Hey, wanna use cookies in your Javascript?! It's as easy as 1-2-3.


Actually it's easier.

1. Grab the following code that was so nicely written by Bill Dortch of
hIdaho Design. Note this is Javascript code, not HTML!!! So download
via the shift-click method or whatnot.

2. Place the following two lines in your HTML document to use cookies:
<script language="JavaScript" src="cookies.js">
</script>

3. That's it... You can now use cookies... You should look through the
code to see how all the functions work.. It's pretty self explanitory.
However, here is the example you can find at the end of the code:
var expdate = new Date ();
FixCookieDate (expdate); // Correct for Mac date
bug - call only once for given Date object!
expdate.setTime (expdate.getTime() + (24 * 60 *
60 * 1000)); // 24 hrs from now
SetCookie ("ccpath",
"http://www.hidaho.com/colorcenter/", expdate);
SetCookie ("ccname", "hIdaho Design
ColorCenter", expdate);
SetCookie ("tempvar", "This is a temporary
cookie.");
SetCookie ("ubiquitous", "This cookie will work
anywhere in this domain",null,"/");
SetCookie ("paranoid", "This cookie requires
secure communications",expdate,"/",null,true);
SetCookie ("goner", "This cookie must die!");
document.write (document.cookie + "<br>");
DeleteCookie ("goner");
document.write (document.cookie + "<br>");
document.write ("ccpath = " +
GetCookie("ccpath") + "<br>");
document.write ("ccname = " +
GetCookie("ccname") + "<br>");
document.write ("tempvar = " +
GetCookie("tempvar") + "<br>");
6. Advanced JavaScript Stuff
(This stuff might be useful someday.)

parseInt, parseFloat, isNaN


Sometimes you want to convert from one type of variable to another.
JavaScript is pretty loose in its variable types. However, certain
situations require certain variables. There are a few functions available
to help you convert from one form to another.

 parseInt
parseInt() will convert a string to an integer. The format is:
parseInt( string [,radix] )

You can optionally specify the radix (or base) of the number. If you do
not specify the radix, JavaScript will try to guess. It is recommended that
you always specify it so there is no possibility of confusion. If the value
can not be converted to an integer, then it returns 0 or NaN depending
on which platform you are using. Example:
the_value = parseInt(some_string,10);

 parseFloat
parseFloat() is the same as parseInt() except that it does floating point
numbers and it does not take a radix argument. It can only do base-10
math. Oh well, no one's perfect. Example:
floating_value = parseFloat("-5.234E+2");

 isNaN
isNaN() can check to see if a value is not a number. This is useful
for the parseInt and parseFloat functions to check if it was not a
valid number. It returns true or false corresponding to whether or not
it was a valid value. Example:
if( isNaN( parseFloat(some_string)) {
alert("That was an invalid value.");
}
else {
alert("That's a valid value.");
}

eval
The eval() command can execute JavaScript code. That may seem pretty
silly, but it can be useful in a few situations. One usefull thing is to give
it a string, and it will convert it to a number. Example:
integer_value=eval("7");

interger_value will then be the integer 7. Another example is to execute


something a little bit more complicated.
the_field_name=getFieldName(2);
alert("The value of the field " +
the_field_name + " is: " + eval(the_field_name +
".value"));

The function getFieldName() gets the name of the nth member of a form
as a string.

Variable Parameter Functions


Sometimes you don't know how many parameters you wish to pass to a
function. The logical solution is to pass an array to the function.
Example:
function stimpy( var ) {
for(var i = 0; i /pre>
The array object has a few properties to make
this easy. First, the .arguments.length
property
to determine the number of elements in the
array. Then you can step through the arguments
by using
the bracket notation .arguments[]. That's it.

src
You can specify external JavaScript code with
the src statement. This is useful if you have
modular code, or you want to break your code
into multiple files. It looks like this:
<script language="JavaScript"
src="some_javascript_file.js">
</script>
This will cause the file some_javascript_file.js
to be inserted at this point.

focus
For some objects, you can force the focus to
appear at certain places. Some objects include
frames, textareas, password fields, etc. It
looks something like this:
top.my_frame.focus();
This will force the focus to appear on
"my_frame".

You can also remove the focus with blur().

You might also like