UCS: The Ultimate Computer Source
A Thinkquest 1999 Entry

Front | Teach | Thinkquest | About UCS

[ History - How? - Internet - Programming - Glossary - Issues - Operating Systems ]

Click here for graphical version

Javascript

  • Preface
  • Embedding
  • Hiding
  • Objects
  • Writing and Quote Format
  • Events
  • Functions
  • Math and Variables
  • Passing Variables
  • The location Object
  • Frames
  • Creating Windows
  • Creating Documents
  • Status Bar
  • Timers
  • onLoad
  • Arrays
  • For/If/Else/Then/While
  • Forms


    Javascript Tutorial - Preface

    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
    Embedding Javascript

    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
    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.
     

    <html>
    <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>

    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.
     
    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.

    Javascript Tutorial - Chapter 2
    Hiding Javascript

    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>
    <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>
     

    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 <!--
    (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 Tutorial - Chapter 3
    Javascript and Objects
     

    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

    document.images[imagenumber]

    Javascript Tutorial - Chapter 4
    Writing and Quote Format

    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" +
                   "There!")

    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

     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")">
    or
    <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

    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!")
    document.write("<p>Hi!")
    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() {
      document.write("<p>Hi!");
    }

    hifunct();
    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() { started a function called hifunct. Anything in-between { and } is part of the function.

    Also note that functions can be run from event handlers.
    Example:

    <input type="button" value="Click me" onClick="hifunct()">

    Javascript Tutorial - Chapter 7
    Math and Variables

    Math and Variables are some of the most important features of programming, no matter what language. Look at this example.

    function addthis() {
    var a = 2;
    var b = 3;

    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
    Passing Variables

    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) {
    alert(txt);
    }

    <form>
    <input type="button" value="Click me"
    onClick="writeinput('Hello')">

    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.'
    Hello was then accepted by the writeinput function as a new variable called txt, which was alerted to the screen.

    Javascript Tutorial - Chapter 9
    The location Object

    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>
    <input type=button value="Yahoo"
      onClick="location.href='http://www.yahoo.com'">
    </form>

    You can combine that with any other event handlers you find later, such as onMouseover, and onMouseout.

    Javascript Tutorial - Chapter 10
    Frames
     
    For this chapter, it requires that you have enough knowledge in frames. If not, check out the HTML Tutorial.

    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
    keep the menu open no matter where the user is on a website.

    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
    vice-versa for both, but frame1, by itself, does not even know that
    frame2 exists!

    If the main document (parent) wants to talk to frame2, all it has
    to do is use this format:
     
    frame2.document.write("Hello, frame2!");

    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
    parent.framename.document as its object name.

    If you want to refer to the parent window (main document) from a frame, you use the parent.document object.
     
    If you wanted a frame to change the entire pages location, thus moving someone, it could do:

    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
    Creating Windows

    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>
    <input type="button" value="Open a new window"
    onclick="openawindow()">
    </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() {
      myWin= open("popup.html", "displayWindow",
        "width=300,height=400,status=no,toolbar=no,menubar=no");
    }

    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
    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

    Closing windows:

    function closewindow() {
      close();
    }

    <form>
    <input type=button value="Close it" onClick="closewindow()">
    </form>

    In this example, it used the close() function. close() closes the window of whatever page its on.

    Javascript Tutorial - Chapter 12
    Creating Documents

    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",
    "width=500,height=400,status=yes,toolbar=yes,menubar=yes");

      flydoc.document.open();
     
      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>");

      docWindow.document.close();
    }

    <form>
    <input type=button value="On-the-fly" onClick="doconthefly()">
    </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
    Status Bar

    The status bar is the gray bar on the bottom of a web browser
    that displays the status of file downloads, network connects, Java
    messages, etc.

    For the status bar, we use an object called 'window.' So the
    status bar becomes window.status (that's what it's called).

    function statbar() {
    window.status = "Behold! I am the status bar!";
    }
    function clearstat() {
    window.status = "";
    }

    <form>
    <input type=button value="Click to change" onClick="statbar()">
    <input type=button value="Clear" onClick="clearstat()">
    </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) {
    window.status = txt;
    }
    function clearstat() {
    window.status = "";
    }

    <form>
    <input type=button value="Click to change"
    onClick="statbar('Behold! I am the statsbar!')">
    <input type=button value="Clear" onClick="clearstat()">
    </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 is an event. Its like saying 'In the event the mouse passes over this link, then do this:'. The action of the event was to change the window.status to 'Click here!'. Return true is to tell the browser not to display anything, since a browsers default action when a mouse passes over a link is to display that links URL. onMouseOut is an event. It's like saying 'In the event the mouse passes off of the link, then do this:'. The action of the event was to clear the window.status.

    Javascript Tutorial - Chapter 14
    Timers

    Timers, or time-outs are used to execute things after a certain amount of time.

    Example:

    function timepop() {
    setTimeout("alert('Times up!')", 3000);
    }

    <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 is a function that declares a timed instruction. In this case, the instruction was to alert a message. The last number, 3000, declares how long the timer should wait. 3000 means 3 seconds. So, 30000 would mean 30 seconds, 300000 would mean 300 seconds. Note the format of setTimeout. a misplaced " ' ( ) or, could seriously mess it up. Like always, this would work also:

    function timepop() {
    setTimeout('alert("Times up!")', 3000);
    }
     

    Javascript Tutorial - Chapter 15
    onLoad (Automatic Javascript)

    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()"> is all you need.

     onLoad is an event. 'Once the body is loaded, do this:'.

    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

    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";
    newArray[1]="Joe";
    newArray[2]="Bob";
    newArray[3]= 8;

    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.
     
    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.

    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 ";
    newArray[1]="There ";
    newArray[2]="How ";
    newArray[3]="Are ";
    newArray[4]"You?";

    document.write(newArray[0])
    document.write(newArray[1])
    document.write(newArray[2])
    document.write(newArray[3])
    document.write(newArray[4])
     

    This could have been combined with a for() loop which you will learn in the next chapter.

    Javascript Tutorial - Chapter 17
    For, If, Else, Then, While

    For If Else Then and While check variables and then run certain instructions determined by what the variables are.

    For:

    for() runs a loop until a certain limit has been
    reached by a variable.

    for(i = 0; i < 6; i++) {
    write.document('Hi');
    }

    This would write Hi 5 times. Now for an explanation: A for loop has 3 arguments. The first sets an integer to a starting number. There are two ways to do this:

    You can declare an integer before the loop:

    var i=0;

    Or you can declare it inside the for loop. Had we done it that way, the for loop would look like this:

    for(var i = 0; i < 6; i++) {

    The second part sets the limit of the loop. The limit is like a check station. Every time a loop is done, it checks to make sure that the limit has not been breached. This limit is that the
    loop can only go on as long as i is less than 6. That means that the loop is executed 5 times in this case.

    The third part increases the integer by one. This is so that every time the loop is done, i is increased by 1. Also every time the loop is done, it would be checked against the second argument, the limit. If i is greater than 5, the loop is over.

    Finally, after that, the for loop uses { and } similar to a function block. Using for loops to do things over and over again can decrease the size of your program, which is good, and makes it easier and more organized to use.

    If:

    if() runs a set of instructions once if a certain variable(s) are
    set to a certain thing(s).

    if(a == 5 || b == 6 && (c == 7 || d == 8)
    alert("Ok...");
    }
    else alert("Not ok.");

    This basically says:

    If a is 5, or b is 6, and as long as c either equals 7 or d equals 8, then alert Ok, but if
    not, then alert not ok.

    This sample just presented was obviously complicated, but it illustrates the power of conditions.

    Else checks against the last if statement made, and must immediately follow the end of an if statement. If the if statement returned false, then it executes its own code.

    Inside the ( and ) of an if() are the parameters that are checked. Here are the following symbols to be used:

    ||  =  or
    &&  =  and
    ==  =  equals
    =   =  make equal
    !=  =  does not equal
    >   =  more than
    <   =  less than
    =<  =  equal to or less than
    =>  =  equal to or more than

    Instructions are checked in the order they are put in. You can enclose a set of instructions ( and ) if you want it to check certain things that would be interfered with by the normal order of how they are put in. This probably sounds really confusing. Just look at the example above.

    Without the ( and ) surrounding the c == 7 || d = 8, Javascript would have interpreted it as this:

    If a is 5, or b is 6, and as long as c equals 7, or if d = 8, then alert Ok, but if not, then alert not ok; which wasn't what we  wanted to say. This is really confusing I'm sure, but once again, it will make sense in a real situation when you encounter it.

    While:

    while() executes instructions until a certain variable equals ordoes not equal something:

    while(a == 5) {
    write.document("Spam!");
    }

    That would go on forever (assuming a == 5) until either the computer crashed or memory ran out. Usually you will put in more than one if statements into it so that there is at least some way of breaking out of the loop.

    Javascript Tutorial - Chapter 18
    Forms

    Forms are usually combined with something like CGI to produce things like email forms, quizzes, or questionnaires. But by using Javascript you can check over answers to make sure that things are filled out.

    function checkform(form) {

    if(form.thename.value == "") {
    alert("You didn't enter a name!");
    }

    else alert("Good!");
    }

    <form name="nameform">
    Input your name: <br>
    <input type="text" name="thename">
    <br><input type="button" value="Test" name="button1"
    onClick="checkform(this.form)">
    </form>

    This simply uses an if statement to check if thename (a text input) contains anything. If it doesn't, it returns an error. If it does, it says 'Good!' You saw a new object, this. this.form is just like it says, it refers to the <form> its in.Its then passed on to the function to be checked.
     
    This all can be used to take some strain out of making CGI programs since its so easy and quick to do in Javascript.




    This concludes our Javascript tutorial.