News Outline Schedule Tutorials Project Tools Links

1: Output

Obviously, a program which does nothing is of no use, so the first commands to learn are the ones which allow you to display output to the viewer. There are a few simple functions built into Javascript which can be used for this, and a few slightly more complex methods. Essentially, it breaks down to there being three ways to produce output from Javascript, in order of difficulty:

  1. Popup alerts and dialogs (warning: these annoy the user)
  2. Output text directly into the HTML code as the page is loading
  3. Altering the HTML code and attributes of the page after it has already finished loading

1.1: Popups

First, a warning - Popups like the ones in this section can be very aggravating to the user, and should be avoided in finished sites - they are however quite useful when developing a page, as you can have updates or warnings about parts of your program going wrong pop up to alert you while you are testing things. Just remember to take them back out before you release the finished product!

The Javascript function to produce a simple popup alert looks like this:

window.alert("text");

This is a builtin function in Javascript, and all functions in javascript follow the same basic format when used:

Function Name - Open Bracket - Parameters - Close Bracket - Semicolon

In this case, there is only one parameter used - a single string of text to put into the popup window. The semicolon is also very important, as it tells the web browser that the current JavaScript command has ended, and the next one should start. In fact, except in some very specific situations, every javascript command should have a semi-colon at the end of it.

The window.alert() popup stops the browser at the moment it is seen in the code, and forces everything to wait until the user hits the "OK" button - this includes other Javascript, and even rendering the HTML code itself. The example below demonstrates this:

<html> <head> <script type="text/javascript"> window.alert("Head tag popup"); </script> <title>Popup</title> </head> <body> <h1>The heading</h1> <script type="text/javascript"> window.alert("Body tag popup one"); </script> <h1>Other heading</h1> <script type="text/javascript"> window.alert("Body tag popup two"); </script> </body> </html>

In each place where a popup is found, the page stops rendering - the one in the head occurs before even the title tag for the page, and if you watch the title when going from this page to the example page, you will see that it does not change to say "Popup" until after clicking OK on the first popup. The two popups in the body area of the page occur mixed in with the HTML code, and as with the head, at each popup the HTML rendering pauses and waits until the popup's OK button is clicked before you can move on to the rest of the page. It is this interrupting nature of the popup which causes it to be an annoyance to users, as they do not want to have to move the mouse around, catch your popups, and make them go away in order to continue using their browser. Many current browsers include an option to completely disable the window.alert() command in Javascript because of this.

1.2: Outputting HTML code as the file loads

The document.write and document.writeln functions both work in very similar ways to each other - they output their string of text into the web document itself. The only real difference between the two is that document.writeln adds a newline character (ie: enter/carriage return) at the end of the string it is outputting. Since HTML browsers automatically collapse whitespace like newlines, tabs and spaces, normally this will amount to very little difference. (Even so, it is sometimes noticeable!) However, if the document.write or document.writeln statement are outputting text in an area that is enclosed by the <PRE> tag. The following code segment demonstrates how this can have an effect, as well as showing how the single newline produced can also have an effect outside of the pre tag.:

<html> <head> </head> <body> <script language="javascript" type="text/javascript" > <!-- document.writeln("writeln and "); document.write("write without "); document.writeln("the use of PRE tags. "); document.writeln("<hr /><pre>"); document.writeln("writeln and "); document.write("write WITH "); document.writeln("the use of PRE tags. "); document.writeln("</pre><hr />"); document.write("A"); document.write("A"); document.write("A"); document.writeln("<hr />"); document.writeln("A"); document.writeln("A"); document.writeln("A"); // --> </script> </body> </html>

As you can see, the document.write() output produced three As with no spaces, but the newline characters produced by document.writeln() are collapsed by the browser into single space characters, just like it would be if you entered three As on separate lines in the source code of an HTML file.

It is important to remember that document.write() and document.writeln() will try to insert their output at exactly the location of their script tag in the HTML file, as though it was part of the HTML code itself. In the above example, multiple HTML tags were included in the output of the commands, and the page was displayed by the browser as though they were actually in the HTML code, rather than printing the tags visibly on the screen. This can be very useful for example, if you want to use Javascript to decide which stylesheet should be loaded by the browser - you place a script in the head of the document which tests to see which stylesheet to use, and then use document.write() to print out the HTML code to load that stylesheet, like this:

<head> <title>boo</title> <script type="text/javascript"> <!-- if (condition) { document.writeln("<link rel="stylesheet" type="text/css" href="potato.css" />); } else { document.writeln("<link rel="stylesheet" type="text/css" href="banana.css" />); }; // --> </script> </head>

The condition in the above code could be anything from the time of day to the user's preferences set in a cookie on the browser.

1.3: Altering the HTML code

The last, and most commonly used method of producing output from Javascript in a web page is by altering the code of the HTML file, or attributes on HTML tags, after the page has already finished loading, and is fully displayed. To do this, we would typically use a DHTML event of some sort to run the code which will change the page. Output of this sort can take many forms, including:

More of this will be discussed later, when we are covering the Document Object Model, but for now, we will occasionally use alterations to the contents of input tags in HTML forms, so here is an example of how that works:

<html> <head> <title>Output!</title> </head> <body> <form name="boo" method="get" action="#"> <input type="text" name="potato" value="starting" /> <input type="button" name="banana" value="Run!" onclick="document.forms.boo.potato.value='It ran.' " /> </form> </body> </html>

In this example, there are a lot of special names that need to be kept track of. First, the name attributes on the form and input tags can be used to uniquely identify them in Javascript when we are using the Document Object Model. In this case, the special identifier document.forms attached (with a .) to the name of the form (boo), which is then attached (with another .) to the name of the form's input tag (potato), which is then also attached (again, with another .) to the value attribute on the input tag, to form document.forms.boo.potato.value - a special construct in Javascript which represents the visible contents of that specific input tag in our HTML file. Adding ='It ran.' afterwards allows us to assign new contents to that form's input tag, just like it was a variable - a part of Javascript which allows us to store information to be worked on and used later in our program.

It should be noted that the rules for the name= attribute's value are the same as the ones for creating the names of Classes in CSS - use only letters and numbers, always start with a letter, and remember that it is case sensitive.

2: Data Storage

In most programs, we will want to store information at one point or another, whether it is to manipulate that information, or just to display it later. As with most programming languages, JavaScript uses variables for this purpose. They are called variables, because their contents can vary as the program progresses. Variables are created in JavaScript using the var command, which goes something like this:

var alphabet;

This creates a new variable, which we can use later in our script at any time we choose. Again, as with the names of Stylesheet Classes, and name= attribute values, your variable names should always follow the standard rules of only letters and numbers, always start with a letter, and remember that it's case sensitive. (ie: Potato is different from potato, which is different from POTATO.)

If you want to create more than one variable at the same time, you can either write out multiple var statements, or you can create more than one variable at a time, like this:

var firstvar, secondvar, number1, number2;

To specify multiple variables at once, you just list them all after the var command, with commas (,) between them.

Like any other statement, it is important to end the var statement with a semicolon.

One thing for people who have programmed in other languages to take careful note of, is that JavaScript variables do not have a type assigned to them. What that means is that when you create a variable in JavaScript, it is not limited to just holding numbers, letters, words, or other things - it can hold any of those, and if your program wants to change what kind of information it is holding partway through your program, it can with no trouble.

When you want to assign data to a variable, you do it by first writing the name of the variable, followed by a single equal sign, and then the data you want stored in your variable. (Like this: variableName = "Value";) You can then get that information back, just by refering to the name of the variable (with no quotation marks) in the place where you want that data to be used. (Like this: document.write(variableName); ) This is demonstrated in the following example, where the variable firstvar is set to contain a string, and secondvar is given a number, and then both are displayed with document.writeln:

<html> <head> </head> <body> <script type="text/javascript" > <!-- var firstvar, secondvar; firstvar = "This is a string"; secondvar = 123; document.writeln(firstvar); document.writeln("<hr />"); document.writeln(secondvar); // --> </script> </body> </html>

As the example shows, the document.writeln function (as well as any other similar output technique) can also use variables as parameters instead of just a string of text. (A string is a set of text which is "contained in quotation marks".

3: User Input

Occasionally we will want to ask the user for information for our program. As with input, there are three main methods to do this:

  1. Use of the window.prompt() popup, which is simple, but can be annoying to the user (and thus should be avoided if you are able)
  2. Reading the contents of HTML form input tags
  3. Reacting to DHTML events being triggered

3.1: window.prompt() popups

The easiest way to do this in JavaScript is with the window.prompt function. This command will open a separate window, which will ask the user for some information, and then will return that information to the program. Since the program needs the information that is being returned, it will not continue until the user hits either the OK or Cancel In the window. If the user hits cancel, the prompt will return an empty, or null value. All information returned from the window.prompt function is in the form of a string, even if the viewer only typed numbers into the window. Here is an example of a program that gets input from the viewer, stores it in a variable, and then displays it:

<html> <head> <script type="text/javascript" > <!-- var onlyvar; onlyvar = window.prompt("Type something!","nothing"); window.alert(onlyvar); // --> </script> </head> <body> </body> </html>

Note that the window.prompt function above requires two parameters! The first was displayed in much the same manner as that of the window.alert function, but the second (after the comma) was used to set the default contents of the user input area. If you do not include the second parameter, the default contents of the user input area will be "Undefined". If you do not want to give a default answer to the users of your web site, you should give an empty pair of quotation marks as your second parameter for the window.alert function, as below:

onlyvar = window.prompt("Type something!", "");

The largest advantage of window.prompt() is that it allows you to ask the user for input before the page has been fully created, and thus you can use that information right away without first needing the user to trigger a DHTML event. Unfortunately, this can also lead to an interruption in the user's experience with the site, and should be avoided wherever possible.

3.2: Reading the contents of a form's input tag

As a smoother alternative, we can read information from a form's input tag, and treat it as though the input tag's value was just a special variable that the user is allowed to alter at will. The document.forms.(form name).(input name).value construct remains the same as before, but now instead of putting it to the left of the =, we use it as though it was just another variable to output, or read information from, like this:

<html> <head> <title>Output!</title> </head> <body> <form name="house" method="get" action="#"> <input type="text" name="boat" value="starting" /> <input type="button" name="car" value="Test?" onclick="window.alert(document.forms.house.boat.value)" /> </form> </body> </html>

The above example also gives an important opportunity to test one of the limitations of the window.alert() function - try typing some simple HTML code, like "This <i>code</i>" into the form box, then click on the button, and you will see that the popup from window.alert() does not interpret HTML code - it always displays exactly and only the contents of the value it is given, as plain text.

3.3: Reacting to DHTML events

This part will be discussed in depth later in the course. DHTML events can be triggered from any interaction the user has with the browser, from clicking on things in the page, to pressing keys on the computer's keyboard. Technically, the method used in 3.2 for telling the browser to read the form input also falls under this category, as the event in question is the "click" event which occurs on the form's button, but it is still actually reading the input from the form's input, rather than solely from the DHTML event that was triggered.

4: Manipulating Data

Now our program can take information from the user, store that information, and display it back to them. The next step is to take that information, and be able to manipulate it in some way. In JavaScript, the two main ways of manipulating data are through simple arithmetic statements, or function calls.

4a: Arithmetic

Arithmetic statements treat strings and numbers differently from each other, and in cases where there are strings and numbers mixed in one statement, it will be treated as if all of the data is in string form. Just like in math however, you can use brackets () to separate a statement from the rest, and have it evaluated first. Here are a few example statements:

<html> <head> </head> <body> <script language="javascript" type="text/javascript" > <!-- var firstvar, secondvar, thirdvar, fourthvar; firstvar = 10 + 7; secondvar = 10 + "hello"; thirdvar = "one " + "two "; fourthvar = "one " + (10 + 23) + 12; document.writeln(firstvar); document.writeln("<hr />"); document.writeln(secondvar); document.writeln("<hr />"); document.writeln(thirdvar); document.writeln("<hr />"); document.writeln(fourthvar); document.writeln("<hr />"); document.writeln(thirdvar + "is what is in the third variable"); // --> </script> </body> </html>

Note that in the statement "one " + (10 + 23) + 12, 10 and 23 are added to get 33, but the 12 on the end is added as though it was part of a string. This is because only the area inside of the brackets is protected, and evaluated separately. The rest of the statement is then evaluated as strings, because one of the elements in it is a string. More types of arithmetic statements will be explained in the next section, which is about javascript operators.

5b: Function Calls

Data in JavaScript can also be manipulated by the use of function calls. The functions called can be either built in functions, or functions created by the user. Creating functions will be covered later, so for now, we will only demonstrate with a few important built in functions. For example, say a program wishes to take a pair of numbers from the user, and add them together. As was shown above, the user input function window.prompt always returns information as a string, so if it was used, then the output from the numbers '1' and '2' would be 12, instead of 3 like they are supposed to be. To correct for this, we will use the built in JavaScript functions parseInt and parseFloat. They can be used to convert strings into integer and floating point numbers respectively. Here is an example:

<html> <head> <title>?</title> </head> <body> <script language="javascript" type="text/javascript" > <!-- var firstvar, secondvar, thirdvar, fourthvar; var output1, output2; firstvar = window.prompt("What is the first number?",""); secondvar = window.prompt("What is the second number?",""); thirdvar = parseInt(firstvar); fourthvar = parseFloat(secondvar); output1 = firstvar + secondvar; output2 = thirdvar + fourthvar; document.write("Before processing, adding them gives: " + output1); document.write("<ht />"); document.write("After processing, adding them gives: " + output2); // --> </script> </body> </html>

parseInt works as follows:

  1. First, if the parameter it is given is really a number (not a string) with no decimal places, (ie: not like 1.5,) it will return that number. Thus, parseInt(2) will return the 2 it was given originally.
  2. Next, if the parameter was really a number (still not a string) but it does have decimal places, (ie: 1.1, 1.9, etc...,) parseInt will chop off the decimal places, and return the whole (integer) part of the number. Thus, parseInt(1.1) and parseInt(1.9) will both return a value of 1 - no "rounding" is done.
  3. Finally, if the parameter is a string, parseInt will begin at the very start of the string, and convert it, one character at a time, into a number, until it finds a character that does not belong in a number, at which point it will stop, and ignore the rest of the string. Thus, parseInt("123horse45") will return the number 123. - the rest of the string, "horse45" will simply be ignored because the "h" is not part of a number. (The "45" at the end are never even looked at - parseInt only looks at the start of the string, not the end.) parseInt will scan along the string from the start, and will only accept characters in this set: 0123456789 and possibly a '-' at the very beginning of the string (to indicate negative numbers.) Thus, parseInt("34.98crayon") will return 34 - the '.' is not allowed, and stops parseInt from continuing.
  4. Last, if whatever is in the string can NOT be turned into a number, parseInt will return a special error code, called NaN (Not a Number) - thus, parseInt("vegetable2") will return NaN

parseFloat works the same, except that in the case of numbers being allowed in, decimal places are kept, and in the string being read, one decimal point is allowed. Thus, parseFloat(6) will return 6, parseFloat(2.9) will return 2.9, parseFloat("34.98crayon") will return 34.98. parseFloat will still return the NaN error code for invalid input, such as with parseFloat("vegetable2").