Why a section on JavaScript, when I hate JavaScript so much? The answer is simple: I was required to take a course on it in college, and so I had to study it. Then I figured I might as well defile my website with what I'd learned.
JavaScript appeals to a lot of people for a couple of very simple reasons. First of all, it's a relatively simple programming language, not a heavyweight like C++ or Java. Secondly, it's easy to implement into web pages, because you do not have to compile your JavaScript code before running it, or even put it into a separate file. Instead, the JavaScript code is actually included within an HTML document. (Actually you have the option of putting the JS code in a separate file, but this is not usually done since it makes things unnecessarily organized. A little later, we'll look at how and why you might want to do this, when we talk about functions.) This ease-of-use has made JS enormously popular with zillions of people who want to program but don't want to be programmers.
Speaking of Java, it should be pointed out that JavaScript has absolutely nothing to do with Java. Java came first, from Sun Microsystems; JavaScript came second, from Netscape, and shared nothing with Java except a name association, a clear attempt at trying to get people to *think* they were related. Judging by how many people confuse the two, Netscape succeeded in this.
Having said that, let's actually look at some JavaScript. Let's start with the basics. How do you add a JavaScript script to a web page? It's simple. Use this syntax:
<script language="JavaScript"> <!-- // YOUR JAVASCRIPT CODE HERE! --> </script>
If you didn't enclose all the JavaScript code within HTML comment tags, browsers which don't recognize JavaScript might display the actual JavaScript code in the web page. Obviously we want to avoid this, hence the comment tags.
Now let's make an actual JavaScript script. We may as well begin with how to make a function, since that's one of the key aspects of any programming language. Here's an HTML document which contains a JavaScript script that's actually a function that gets run three times.
<SCRIPT language="JavaScript"> <!-- functionname(); functionname(); functionname(); function functionname() { document.write("This gets printed three times!<BR>"); } --> </SCRIPT>
This script is simple and to the point; It creates a function, and it calls this function three times. Notice that it's okay to call the function at a point in the program before you actually define the function itself. This is perfectly acceptable, although most programmers prefer to define their functions first to get them out of the way, then flesh out the actual main program.
A few other points bear mentioning. The <BR> tag is actually encased inside the quotation marks and displayed in the browser window as a literal string. This is fine, as HTML tags will still perform their normal HTML functions even though they're being printed from within a script. Also note that the lines in the program do not actually need to end with semicolons. Unlike C, JavaScript does not require them. The semicolons are included here simply because it's good programming form. (If you get into the habit of writing lines of code without terminating them in a semicolon, you're going to have been spoiled once you're finished playing with JavaScript and you go back to C or Perl.)
Finally, notice how we print text to the screen: document.write is actually a function in itself, built into JavaScript. Properly speaking, this is actually a method, which is simply defined as a function that's called through an object. In this case, the object is document, an object built into JavaScript which refers to the current HTML document (web page). The write method of the document object is called using the standard syntax of object.method, and given an operand (in this case, the string that we want to print). You might also see people using the writeln (write line) method, which is exactly the same as write, except that it adds a newline character to its output. Note that HTML generally ignores this newline character, unless you're within a <PRE> tag.
Now that we've seen how to make a function, you might want to know a bit about how to use them. Unfortunately, because JavaScript is usually used for small, simple scripts, and its code is typically inserted within a single HTML document, functions might seem to have limited use unless you happen to want to use the same subroutine numerous times on the same webpage. In actuality, however, this is the point where putting your JavaScript into a separate file (rather than encasing it in your HTML file) becomes useful. As in C, you can create your own library of "header files", each of which contains frequently-used functions or definitions, and include these files with your code with a single line referring to the filename. The syntax to include a separate script file in your web page looks like this:
<SCRIPT SRC="c:\blah.js"></SCRIPT>
This would load c:\blah.js as a JavaScript program (stand-alone JavaScript scripts are typically given a .js extension). Within that file, you can have whatever functions you want, and you will then be able to call those functions through scripts in THIS file. Thus, you are able to load your own JavaScript routines through a single line. This is handy if you have several JavaScript functions that you want to repeatedly use across several web pages.
JavaScript's if and else statements look just like C's, and for good reason:
<SCRIPT language="JavaScript"> <!-- var number=10; if (number==10) {document.write("number equals 10!");} else {document.write("number does not equal 10!");} --> </SCRIPT>
Newbie reminder: The else statement isn't necessary to use if; You can have an if without an else, but you can't have an else without an if.
Possibly the most important use of JavaScript is to process information entered by the user in an HTML form. Therefore, we should learn how to process form elements. To illustrate, here's a sample HTML document which simply returns to the user what s/he typed:
Please enter some stuff: <FORM onSubmit="cooljsprocess()"> <INPUT TYPE=text NAME=myinput> <INPUT TYPE=button VALUE="OK" onClick="cooljsprocess()"> <script language="JavaScript"> <!-- function cooljsprocess() { alert("You entered the following: " + document.forms[0].myinput.value); } --> </script>
Clearly, this is a pretty simple JavaScript program, at only two lines (well, three if you count the function-closing bracket that I put on the third line). It should also be clear that the HTML form calls the cooljsprocess() JavaScript function when you click the OK button. The interesting line, of course, is the one that begins with alert. alert is a JavaScript function which simply pops up a dialog box on the screen with some message in it. The other interesting part of this line is document.forms[0].myinput.value, which is (read from right to left) the value of the myinput form element in form number zero (0) of the document. Form zero is always the first form, and the forms are then numbered in sequential order from there. In this case, the document has only one form, which keeps things simple.
Now let's look at a slightly more complicated JS program, which illustrates how to work with numbers.
Please enter a number: <FORM onSubmit="cooljsprocess()"> <INPUT TYPE=text NAME=number> <INPUT TYPE=button VALUE="OK" onClick="cooljsprocess()"> <script language="JavaScript"> <!-- //Do NOT put the line to parseInt here. If you do so, the line will be run //BEFORE cooljsprocess has been called by pushing the button, and therefore, //the value for "number" will be undefined (because the user has not yet //input anything), and parseInt will return a NaN. (Not A Number) //The line to parse the value for "number" must be inside cooljsprocess, so //that it will not be loaded until the user has actually had a chance to //enter something and click the button. function cooljsprocess() { //"number" still exists as a string. It must be parsed into an integer //variable using the parseInt function. parseInt will return a NaN (Not A //Number) value if it processes a variable that is not a number. var jsnum = parseInt(document.forms[0].number.value) //The only way to check if a variable is NaN is by using the isNaN function. //isNaN returns 1 if the analyzed variable is NaN, and 0 if it is not. if (isNaN(jsnum)==1) { alert("You didn't enter a number!"); } if (isNaN(jsnum)==0) { alert("You entered the number: " + jsnum); } } --> </script>
As you've probably guessed by now, using double-slashes (//) creates a comment in JavaScript. Anyway, the first interesting line in this program is the one using parseInt. parseInt takes a particular form input's value (in this case, we see it reading the value of the input called number) and makes it into an integer-type JavaScript variable. This is important because otherwise, all the form inputs are read as strings in JavaScript, and thus you could not do math with them (such as adding them to each other, etc.) In this case, we use var jsnum to create a JavaScript variable called jsnum, which is the JavaScript number variable for this program. Speaking of var, you should also know that when creating variables in JavaScript, these variables are not given a type. Unlike most programming languages, where you create an integer-type variable or a string variable, JavaScript just has plain variables, and the JavaScript interpreter is supposed to be smart enough to figure out whether the variable is being used as a number or a text string. This is much simpler, and this is precisely the reason that most variables in JavaScript don't usually need to be declared before being used.
As the comments in the code mention, parseInt returns a special type of variable called NaN (Not A Number) if it processes a variable that's not a number. As the code comments also helpfully note, the only way to check if a variable is NaN is by using the isNaN function. Therefore, the program then uses isNaN to check if jsnum is a number, and if so, it tells you exactly what number you entered. If you did not enter a number, the program chides you for your error.
Let's see a program that does some work with numbers now. This is where things get fun and we start doing operations on the variables:
<FORM onSubmit="docalc()"> First number: <INPUT TYPE=TEXT name=num1><BR> Second number: <INPUT TYPE=TEXT name=num2><BR> <INPUT TYPE=RADIO NAME=operation VALUE="add">Add <INPUT TYPE=RADIO NAME=operation VALUE="subtract">Subtract <INPUT TYPE=RADIO NAME=operation VALUE="multiply">Multiply <INPUT TYPE=RADIO NAME=operation VALUE="divide">Divide<BR> <INPUT TYPE=BUTTON VALUE="Calculate" onClick="docalc()"> <script language="JavaScript"> <!-- function docalc() { var jsnum1 = parseInt(document.forms[0].num1.value) var jsnum2 = parseInt(document.forms[0].num2.value) if (document.forms[0].operation[0].checked == 1) {num3 = jsnum1 + jsnum2;} if (document.forms[0].operation[1].checked == 1) {num3 = jsnum1 - jsnum2;} if (document.forms[0].operation[2].checked == 1) {num3 = jsnum1 * jsnum2;} if (document.forms[0].operation[3].checked == 1) {num3 = jsnum1 / jsnum2;} //alert(num3); if (document.forms[0].operation[0].checked == 1) {alert(jsnum1 + " plus " + jsnum2 + " equals " + num3 + ".");} if (document.forms[0].operation[1].checked == 1) {alert(jsnum1 + " minus " + jsnum2 + " equals " + num3 + ".");} if (document.forms[0].operation[2].checked == 1) {alert(jsnum1 + " times " + jsnum2 + " equals " + num3 + ".");} if (document.forms[0].operation[3].checked == 1) {alert(jsnum1 + " divided by " + jsnum2 + " equals " + num3 + ".");} } --> </script>
The first part of this document sets up an HTML form with two text-input fields where you are intended to type a number. Below that are the four basic arithmetic operations, and a button labeled "Calculate". After typing two numbers, selecting your operation, and clicking the button, the JavaScript script then performs that operation on the numbers and shows you the result. Magnificent, isn't it?
Most of this JavaScript program should be clear. The only part that might bear some explaining is the document.forms[0].operation[x].checked part. This is a property which specifies whether operation[x] is checked, where x is a number of the operation form element. As you have probably guessed, the radio buttons which make up the operation element have been automatically numbered from first to last, the first beginning at number zero. Add is operation[0], subtract is operation[1], and so on. Once the program has determined which radio button was checked by the user, it performs the necessary arithmetic, and displays the result in a convenient alert box. If you'd rather just display the result of the math without the accompanying "x blah blah y equals whatever", un-comment the commented alert command and take off all the ifs after it.
Here's how to attach JavaScript functions to a drop-down list box:
<FORM> <SELECT name=colorlist onChange=dropdownlistfunc()> <OPTION value=blue>Blue <OPTION value=red>Red <OPTION value=purple>Purple </SELECT> <SCRIPT> function dropdownlistfunc() { alert("You selected " + document.forms[0].colorlist.value + ".") } </SCRIPT>
That should be enough JavaScript for now. At least now when you're a grandparent you can tell your grandchildren about how you battled the horrific JavaScript monster, and won.