Java Script
Java Script
Java Script
Introduction
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>
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>
<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()">
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.
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:
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.
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.
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.
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
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
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;
}
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;
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 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;
}
<SCRIPT LANGUAGE="JavaScript">
<!-- hide JavaScript from older browsers
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.
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
}
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;
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>
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");
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 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"])
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.
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",
"</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.
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);
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.
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.
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.
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.
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.
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.
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.
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.
onUnload
The onUnload event occurs whenever the user leaves a document.
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:
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>
<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
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
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
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");
The function getFieldName() gets the name of the nth member of a form
as a string.
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".