Front | Teach | Thinkquest | About UCS
[ History - How? - Internet - Programming - Glossary - Issues - Operating Systems ]
Javascript is a programming language that has the ability to run in
web browsers like Netscape, and Microsoft Internet Explorer. The good thing
about this is that more advanced features can beput into webpages that
could not be done with ordinary HTML.
Javascript should not be confused with Java. Java is a totally different,
more advanced object-oriented language that has more functionality and
can be used to write much more powerful programs.
Another difference between Java and Javascript are their creators. Java
was created by Sun Microsystems, whereas Javascript was developed by Netscape.
To use this tutorial, you need no compilers or interpreters. Javascript
is built into Netscape and Microsoft Internet Explorer. All you need to
do to 'compile' a Javascript program is create a webpage, and embed the
Javascript code into the page. You'll learn about that in the first chapter.
This tutorial will assume you have a pretty good knowledge of HTML.
Also note: After you learn about embedding Javascript, all examples
or code snippets are not as is, they are intended to be put in the Javascript
code area as you'll learn later. If you encounter any HTML tags such as
<FORM> that are not inside a Java-script code, they are intended to
be placed in the body section of the page.
Javascript Tutorial - Chapter 1
Before you start learning the programming language, make sure you have
the necessary software. All you need is a Javascript enabled web browser.
Netscape (v 2.0 and up) or MSIE (v 3. and up) are the best choices.
Also, this tutorial assumes you are knowledgeable in HTML. If you are
not, don't worry! Just check out the HTML Tutorial on this site.
Another thing that will help you in learning is if you know a programming
language like Java or C. This is not required, but it will make learning
functions and the like much easier. Of course
<html>
As you can see, the tag to switch to Javascript is <script>. The
format is <script language="Javascript">. A Javascript portion of code
can be put anywhere inside the <script>. Of course, to end a Javascript
code, put </script> after the code is finished. Some Javascript events
(you'll learn later) can be placed in various places outside of the <script>
tag.
Javascript Tutorial - Chapter 2
Before we start the actual language, you must consider what would happen
in the event a browser that doesn't support Javascript enters your site.
Your Javascript code would be ordinary text to that person on the ancient
browser, and it would probably muck the page up.
<html>
What did that accomplish, you might be asking? If a non Javascript browser
sees <script language="Javascript">, it doesn't understand it, and treats
the rest like ordinary HTML. However, since it is treating it as HTML code,
when it encounters the <!--
Javascript Tutorial - Chapter 3
In order for Javascript to write things to a webpage, or for it to change
part of a webpage, like changing a graphic when a button is clicked, Javascript
must have a way of referring to different parts of the page. Each webpage
has a 'hierarchy,' a chain of properties of a webpage listed in order of
what they are connected to. In Javascript, things are 'objects.' The main
part of the webpage (the actual webpage is an 'object' is defined as document.
As you saw in Chapter 1, document.write("This is Javascript!") would write
"This is Javascript!" in the document, which would just be the body of
the page.
Objects can be referred to off of each other. For example, if you wanted
to access an image on the page, you could do
Javascript Tutorial - Chapter 4
In the first chapter you saw how to write to the webpage. In this chapter
it will be described a little more in depth.
To write to the webpage, use this format:
document.write("Hello");
But also know, this will work too:
document.write('Hello');
Javascript accepts either ' or " for quotes, but not both at the same
time. You will see an example in the first part of Chapter 5.
If you ever want to actually write a ' or " without intending it as
a formatting symbol, if you replace it with /' or /" instead of ' or "
Javascript will just print it as it is.
Later in this tutorial you will want to combine text with variables
to write or maybe a multi line text that's all in the same document.write
space.
document.write("Hello" +
This would make a multi lined document.write that was all in the same
place. This will be useful later on.
or to write variables and text together:
document.write(somevar + "Hello" + another var);
The variables/text would be printed in order of how they were listed.
These weren't the best examples of how to combine text, but just don't
be confused if you see it later on in the tutorial.
Javascript Tutorial - Chapter 5
Events make up the interactive part of Javascript. An event could
be the mouse passing over an image, if a button is clicked, or a link clicked.
This makes excellent possibilities for interactive quizzes, or text games.
<input type="button" value="Click me" onClick="alert('Hi')">
This makes a button titled 'Click me.' When clicked (onClick), it invokes
the alert function of Javascript. alert() pops up a window with a message.
In this case, when someone clicks on the button, it will display the message
(Hi) in a small popup window. Note the use of " '' " in the onClick part,
which shows how you can't combine a ' and " as a quote for something. The
reason you can't do:
<input type="button" value="Click me" onClick="alert("Hi")">
because the computer must be able to differentiate between what is the
event-handler (alert()) and what
is actually inside the alert(), which
is Hi.
There are more event handlers such as
onMouseover,
that if not seen later in the following chapters will be at a reference at the end of
this tutorial.
Javascript Tutorial - Chapter 6
Functions are used to make things in Javascript easier to do. Many functions
like alert() are built in functions, but in this chapter you will learn
what functions really are, how to define custom functions, and how
to access functions.
Functions hold lists of instructions, like an alias. So every time
you access a function, it performs pre-defined actions. Look at this example.
document.write("<p>Hi!")
This of course is just an example, no one would really go all the way
to use Javascript just to display 3 lines, but we'll just go along with
it.
This is all fine and well, except that it would be easier and way more
efficient to have a function do it for you. Its not that big a deal of
course to type 3 lines, but if you imagine what would happen if you had
a 80 line code that you wanted to do 5 times, it would save you a lot of
typing and a lot of time and a lot of space to make a function to carry
out what you want the code to do.
Consider this example instead:
function hifunct() {
hifunct();
As you can see, instead of doing document.write's, it is all now in
one easy function. So if you wanted to write it 10 times, all
you'd need to do is run the function. This is more useful if the function
contains more than a few lines, as it would then save much space.
function hifunct() { Also note that functions can be run from event handlers.
<input type="button" value="Click me" onClick="hifunct()">
Javascript Tutorial - Chapter 7
Math and Variables are some of the most important features of programming,
no matter what language. Look at this example.
function addthis() {
var total = a + b;
alert(total);
addthis();
Many things to look at here. To define a variable, you use this format:
var (variablename) = (startingnumber);
You can also use operators (+ / - *) to define what a variable is, so
you can have totals and the like.
You also saw something new in the alert function. There was a variable
between the () in alert().
alert(total) would bring up a pop up window and
display the variable.
You can also use something like
a = b; or a = 4;.
Javascript Tutorial - Chapter 8
There will come a time later in this tutorial, and in programming when
you will need to pass a variable to a function.
function writeinput(txt) {
<form>
Of course, this didn't exactly accomplish anything, but it was to demonstrate
how to pass information to a function.
onClick executed the function writeinput
with the arguments: 'Hello.'
Javascript Tutorial - Chapter 9
As you saw before, Javascript refers to objects when it wants to refer
to some specific webpage attribute.
Another important object is the location object. It controls what address
the person is at. For instance, you could have your page automatically
skip to a new page, if the current page was old or out of date.
location.href is the string we want to modify to change what website
address we're at. For example, we could make a button that sent someone
to a page.
<form>
You can combine that with any other event handlers you find later, such
as onMouseover, and onMouseout.
Javascript Tutorial - Chapter 10
Frames are used to divide a page into smaller sections. For example,
you could split a page into 2 sections, a menu bar and a main body area.
This would have the advantage of being able to
The only problem is, how will Javascript 'talk' to the other frames?
Javascript talks to other frames by relay messaging. Remember how in
frames you can assign names to a frame in order to load links in a different
frame? Javascript uses frame-names in communicating, so always name your
frames.
frame1 can contact document, and frame2 can contact document, and
If the main document (parent) wants to talk to frame2, all it has
If a child frame wants to access another child frame, it uses this format:
parent.frame1.document.write("Hello frame1!");
In essence, frame1 went back to document, document has a frame2 to talk
to, so frame1 sent its message relayed through parent. So if you
want to refer to a different frame, just use
If you want to refer to the parent window (main document) from a frame,
you use the
parent.document object.
parent.location.href="http://www.newaddress.com";
Or you could change one frames address from another:
frame1.parent.location.href="http://www.newaddress.com";
Or you could change one frames address from the parent:
frame2.location.href="http://www.newaddress.com";
Javascript Tutorial - Chapter 11
One of the most used Javascript features (especially for advertising
purposes has been the ability for Javascript to open windows.
function openawindow() {
thewin = open("http://www.mysite.com/popup.html">
and then in the <body> section
<form>
This would create a button that when clicked would open a new browser
window and would load the designated page.
You can control attributes of the opened window:
function openWin2() {
displayWindow
is the name of the popup window. You can name a window
to anything you want when you use open().
Note: You must follow that formats, any spaces in the width=300 line
will be interpreted as an error.
You can see that we specify the properties in the string
"width=400,height=300,status=no,toolbar=no,menubar=no".
Please note that you must not use spaces inside this string.
Here is a list of the properties a window can have:
directories - yes|no
Closing windows:
function closewindow() {
<form>
In this example, it used the
close() function.
close() closes the window
of whatever page its on.
Javascript Tutorial - Chapter 12
A special feature of Javascript is the ability to generate a webpage
or another type of document for instant use.
Its not really that special or difficult to use, it just is pretty useful.
It makes use of document.write
Suppose you wanted a popup window to open with a premade page. The advantage
of this is speed. The actual page would not have to be accessed had you
used the normal way (by just making a .html file). The web browser is fed
the information when it loads the first page, so it cuts down on page loading
by half. If you utilize this a lot on your web page, you'll find it loads
much quicker. Observe the example below:
function doconthefly() {
flydoc = open("", "docWindow",
flydoc.document.open();
docWindow.document.close();
<form>
A few new things have been done in this example. In the
open() function,
instead of opening a file, it was left blank so that an empty window would
be opened. Then,
docWindow.document.open() opened the window to be written
to. Note: a document.open() is different from
the actual open()
function.
A document cannot be written to unless it is 'open' using the document.open
function. Then, you saw a normal document.write used to write in normal
html tags for a page. Before you're done writing to a document, you must
ALWAYS close the window using document.close(). Just like open(), close()
and document.close() are different functions. close() would close the window,
while document.close() would just stop the ability to write to a document,
to close off its file access.
After that, a simple button to run the function. In later chapters you
will learn how to automatically run functions, without needing buttons.
And note, just like anything else, document is just an object, so the
write function can be used in any object representing a page, like:
parent.frame3.document.write("Frame 3");
or something of that nature.
Javascript Tutorial - Chapter 13
The status bar is the gray bar on the bottom of a web browser
For the status bar, we use an object called 'window.' So the
function statbar() {
<form>
As you saw, status is just like a variable off of the window object.
You could combine this with variable passing as you saw before in this
tutorial:
function statbar(txt) {
<form>
The status bar is more useful than to use to just make corny little
messages. For instance, you could combine this with links. Whenever the
mouse passed over a link, it would change the status bar. We will use some
new functions, so pay attention.
<a href="click.html" onMouseOver="window.status='Click here!';
return true;" onMouseOut="window.status='';">Click here!</a>
onMouseOver
Javascript Tutorial - Chapter 14
Timers, or time-outs are used to execute things after a certain amount
of time.
Example:
function timepop() {
<input type=button value="Click and wait 3 seconds" onClick="timepop()">
This would make a button, that when clicked, would alert a message after
3000 milliseconds, or 3 regular seconds.
setTimeout function timepop() {
Javascript Tutorial - Chapter 15
Throughout the tutorial so far you have seen Javascript code executed
by means of clicking a button. But you probably will not always want a
button, and would just like for the code to be run automatically.
<body onLoad="function()"> onLoad If you need to run more than one function in any event, just make one
function that runs them all and then use that!
Javascript Tutorial - Chapter 16
Arrays are bundles of variables stored into one easy name. Say you had
50 names you wanted to use in a program. Instead of making 50 variables,
which would make your program cluttered, messy, and disorganized, you can
use an array to store them all.
Declaring an array is incredibly simple. JavaScript, thankfully, is
extremely flexible when using arrays. You don't need to declare how big
it is, nor do you have to declare whether an item is a text variable or
a number variable (integer).
newArray= new Array();
newArray[0]="Jim";
And there's the array. To refer to an item in the array, you can just
use it as
newArray[#] where
# is a number from (obviously) 0-3. Now, for
an explanation:
Before you use an array, you must take a second to declare it. As you
saw, its a simple
newArray = new Array(); The good thing about Javascript is that it automatically determines
the size of the array. The size of the array in this case is 3. (By the
way, arrays always start with 0). Javascript arrays however, will not 'shrink.'
This means if you added another line to our example:
newArray[499]="Billy";,
then there would be 500 entries into the array... that would consume a
lot of memory and make the program inefficient. So keep the numbers in
order, the smaller the better.
Arrays can be declared anywhere in the Javascript code and you can choose
whatever name you want.
Now lets see an array in action.
newArray = new Array();
newArray[0]="Hi ";
document.write(newArray[0])
This could have been combined with a for()
loop which you will learn
in the next chapter.
Javascript Tutorial - Preface
Embedding Javascript
if you don't know C or Java, that's no problem at all, don't be compelled
to force yourself to learn C or Java just to help you in Javascript.
<head>
<title>Javascript</title>
</head>
<body>
This is regular Html, nothing fancy here.
<script language="JavaScript">
document.write("This is JavaScript!");
</script>
<p>Back in HTML again.
</body>
</html>
Another thing in the example was document.write("This is Javascript").
You'll learn more about that in the third chapter, as it will explain how
Javascript refers to writing things and how it deals with objects in a
webpage.
Hiding Javascript
<head>
<title>Javascript</title>
</head>
<body>
This is regular Html, nothing fancy here.
<script language="Javascript">
<!-- hide from old browsers
document.write("This is JavaScript!");
// -->
</script>
<p>Back in HTML again.
</body>
</html>
(the comment tag) the browser now thinks that the Javascript code is
a comment, and doesn't display the Javascript code in the webpage. So,
whenever you write a Javascript code/program, be sure to use the comment
trick to hide Javascript from browsers that don't support Javascript.
Javascript and Objects
document.images[imagenumber]
Writing and Quote Format
"There!")
Events
or
<input type="button" value="Click me" onClick='alert('Hi')'>
Functions
document.write("<p>Hi!")
document.write("<p>Hi!")
document.write("<p>Hi!");
}
hifunct();
hifunct();
Example:
Math and Variables
var a = 2;
var b = 3;
}
Passing Variables
alert(txt);
}
<input type="button" value="Click me"
onClick="writeinput('Hello')">
Hello was then accepted by the writeinput function as a new variable
called txt, which was alerted to the screen.
The location Object
<input type=button value="Yahoo"
onClick="location.href='http://www.yahoo.com'">
</form>
Frames
For this chapter, it requires that you have enough knowledge in frames.
If not, check out the HTML Tutorial.
keep the menu open no matter where the user is on a website.
vice-versa for both, but frame1, by itself, does not even know that
frame2 exists!
to do is use this format:
frame2.document.write("Hello, frame2!");
parent.framename.document as its object name.
If you wanted a frame to change the entire pages location, thus moving
someone, it could do:
Creating Windows
}
<input type="button" value="Open a new window"
onclick="openawindow()">
</form>
myWin= open("popup.html", "displayWindow",
"width=300,height=400,status=no,toolbar=no,menubar=no");
}
height -
number of pixels
location - yes|no
menubar - yes|no
resizable - yes|no
scrollbars - yes|no
status -
yes|no
toolbar - yes|no
width -
number of pixels
close();
}
<input type=button value="Close it" onClick="closewindow()">
</form>
Creating Documents
"width=500,height=400,status=yes,toolbar=yes,menubar=yes");
flydoc.document.write("<html><head><title>Quick Document");
flydoc.document.write("</title></head><body>");
flydoc.document.write("<center><font size=+3>");
flydoc.document.write("This was made with Javascript! ");
flydoc.document.write("</font></center>");
flydoc.document.write("</body></html>");
}
<input type=button value="On-the-fly" onClick="doconthefly()">
</form>
Status Bar
that displays the status of file downloads, network connects, Java
messages, etc.
status bar becomes window.status (that's what it's called).
window.status = "Behold! I am the status bar!";
}
function clearstat() {
window.status = "";
}
<input type=button value="Click to change" onClick="statbar()">
<input type=button value="Clear" onClick="clearstat()">
</form>
window.status = txt;
}
function clearstat() {
window.status = "";
}
<input type=button value="Click to change"
onClick="statbar('Behold! I am the statsbar!')">
<input type=button value="Clear" onClick="clearstat()">
</form>
Timers
setTimeout("alert('Times up!')", 3000);
}
setTimeout('alert("Times up!")', 3000);
}
onLoad (Automatic Javascript)
Arrays
newArray[1]="Joe";
newArray[2]="Bob";
newArray[3]= 8;
Now, you might have noticed that newArray[3] does not have " and ".
This means that it is not a text variable, instead, it is an integer. Anything
without ""'s is treated as such. However, if you try newArray[4]=abc; you
will get an error.
newArray[1]="There ";
newArray[2]="How ";
newArray[3]="Are ";
newArray[4]"You?";
document.write(newArray[1])
document.write(newArray[2])
document.write(newArray[3])
document.write(newArray[4])