![]() |
![]() |
Input and 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:
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:
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:
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.
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.:
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:
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.
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:
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.
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:
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:
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:
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".
Occasionally we will want to ask the user for information for our program. As with input, there are three main methods to do this:
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:
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:
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.
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:
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.
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.
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.
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:
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.
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:
parseInt works as follows:
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").