Introduction
Javascript, also known as ECMAscript, is a widely used programming language that is available in such diverse applications as web browsers and Adobe Photoshop. There are tons of books and web resources devoted to helping programmers work with Javascript, so why this web page?
The answer is: to avoid those tons of books and web resources and to get you started using Javascript so you can add dynamic features to web pages as quickly and easily as possible. As programming languages go, Javascript is not very complicated, and this page should be enough both to give you a reading knowledge of the language and to give you a good understanding of the fundamentals of how the language works. When you finish, you should understand what Javascript code does if you see it, you should be able to write simple code on your own, and you should be able to take someone else’s Javascript code and adapt it to your own needs. At that point you might want to start tackling those tons of detailed reference material on the language that are available elsewhere.
When you see a term that looks like this, it is defined in the Glossary.
Javascript Elements
Variables, Values, and Expressions
Javascript code consists of statements that are executed by the Javascript interpreter that is built into virtually all web browsers (Internet Explorer, Firefox, Opera, Safari, ...). An assignment statement gives a value to a variable. For example, here is an assignment statement that gives the numerical value 3 to a variable named sampleVariableName :
sampleVariableName = 3;
As you can see, an assignment statement consists of a variable name on the left-hand side of an equal sign, a value on the right-hand side of the equal sign, and a semicolon at the end of the statement.
Statements are executed sequentially. For example, sampleVariableName ends up with the value 7 after this code gets executed:
sampleVariableName = 3; sampleVariableName = sampleVariableName + 4;
With this example, you can also see that putting a variable on the right-hand side of the equal sign gets the current value of the variable, which can be used either alone or as part of an expression to compute the value that is assigned to the variable on left-hand side of the statement.
Arithmetic expressions consist of any combination of add (+), subtract (-), multiply (*), and divide (/) operations applied to numbers and variables. Use parentheses to control the order of evaluation. For example, the expression 1 + 2 * 3 will do the multiplication before the addition, but you can force the addition to be done first using parentheses: (1 + 2) * 3. That is, the value of 1+2*3 is 7, but the value of (1+2)*3 is 9.
There is a logical sequence controlling what you can do with a variable: before you use it in an expression you have to give it a value, and before you give it a value, you have to declare it. You declare a variable using the var keyword. You can combine the declaration with the assignment of an initial value:
var sampleVariableName = 0;
As you might guess, you can’t use a keyword as a variable name:
var var = 0; // Won't work!
Aside from not using keywords, there are a few rules for how you make up variable names: they are case sensitive, so that sampleVariableName is different from SampleVariableName, they can have digits in them (first20, for example), but the digits can’t be at the beginning. Other than letters and digits the only other character you can use in a variable name is the underscore character ( _ ). No spaces, no punctuation. And it’s not a rule of the Javascript language, but it will make everyone’s life a lot easier (including your own) if you use meaningful names for your variables.
The “//” in the previous example starts a comment. Comments are messages you put in your code for people to read (to help them understand what’s going on), but they are ignored by the Javascript interpreter. If you want a comment to span multiple lines, put them inside /* ... */ instead of starting with //.
In addition to numbers, Javascript includes string values. Strings are simply sequences of characters surrounded by quotation marks. Unlike many other programming languages, it doesn’t matter whether you use single or double quotes around a string as long as the beginning and ending quotes match each other:
var aVariable = 120 + 3; aVariable = "123"; aVariable = '123'; aVariable = '1' + 2 + "3"; aVariable = ''; aVariable = "Don't touch that button!";
The first statement declares aVariable and assigns it a numerical value of 123. The next three statements assign a string value to the variable consisting of the three characters '1', '2', and '3'. The first two strings illustrate that you can use either single or double quotation marks. The third one shows several things: you can combine strings that were defined using either type of quotes, you can use + to connect strings together (“concatenate” them), and if you concatenate a numerical value (2, in this case) with a string value, the number is automatically converted to a string for you. That is, the + in the first line adds two numerical values to give the number 123, but the two +'s in the fourth line concatenate three strings to give the string value “123”. The fifth line shows that you can have a string with no characters in it. The last line shows that you can put a single quote inside a string that is surrounded by double quotes. (The other way around works too.)
Functions
Functions are statements that get executed as a group. You define a function using the function keyword:
function sampleFunction() { var a = 3; var b = 4; return a + b; }
The first line consists of the function keyword, the name of the function (sampleFunction ), and a pair of parentheses. The group of statements that make up the function are enclosed in curly braces. Functions may include a return statement, and return statements may include a value that is returned by the function. You can get the function to execute by calling it as part of an expression:
aSampleVariableName = sampleFunction() + 2;
In this example, the function returns the value 7, which gets added to 2, and the value 9 gets assigned to aSampleVariableName.
Some functions don’t return a value, or they return a value that is irrelevant to the logic of your code. In those cases, the function call alone is a complete statement, without any assignment (equal sign) involved. For example, there is a function built into Javascript named alert that displays a message on the screen, but doesn’t return a value. It could be called like this:
alert( "This is a sample message" );
This example illustrates the other key thing about functions: you can pass parameters to functions. In this case, a string parameter is being passed to the alert() function. The statements inside the alert will cause a message window to pop up with the parameter value displayed in it.
Here is the definition of a function that receives two parameters and returns their sum:
function sum( a, b ) { return a + b; }
Here are two calls to this function. What value does each one
assign to ans ?
Move your
mouse over the code to see if you are right:
ans = sum(120, 3);
This statement assigns the number 123 to ans.
ans = sum('12', '3');
This statement assigns the string "123" to ans. Remember: + adds numbers, but it concatenates strings.
(This distinction between numbers and strings may seem a bit obscure at this point, but it will be critical for getting many dynamic effects to work.)
One of the reasons there is so much published material on Javascript is that there are many, many predefined functions built into Javascript, and documenting them all takes a lot of words. Fortunately, you don’t really need to know a lot of them to get started, and a few of them will be covered below.
Objects
The last element of Javascript we consider is the object. Normally you will be working with objects that the browser has already created, but here’s an example of one way to create a simple object:
var obj = new Object(); obj.a = 3; obj.b = 4; obj.fun = function() { return this.a+this.b; }; alert(obj.fun());
Here’s what is going on: the first line creates a new object and gives a reference to the object to a variable named obj. The keyword new tells Javascript to allocate some memory for this object. There are other things Javascript can create using new, but for now we are looking only at the one named Object, which must be capitalized and spelled exactly as shown. The parentheses at the end are necessary, too.
The next two lines create two new variables in the object referenced by obj. Note that a dot separates the reference to the object from the variable inside the object. Other than that, variables inside objects are just like regular variables: they can appear on either the left or right side of assignment statements, and they can hold numbers, strings, or any of the other types of value that we haven’t talked about yet.
There are a couple of things to note about variables inside objects: the first is that you do not use var when you want to create one, you just assign an initial value to it and it gets created automatically. The second item is of interest primarily if you already know another programming language, and it’s that in Javascript you don’t have to declare what variables an object is going to contain ahead of time. Just pick a name, assign a value to it, and it gets created.
The fourth through seventh lines show how you can put a function inside an object. Technically, the function is separate from the object and the object variable (fun in this case) holds a reference to it, but that’s not a key concept at this point. What is important is to note that the function doesn’t have a name. Remember, when defining a function, you usually put the keyword function, followed by the name of the function, followed by the parentheses. Finally, note that inside the function, the variables in the object can be referenced using the special object name, this. (Yes, you could also refer to the variables as obj.a and obj.b, but that would take away one of the things you can do with object, so using this is normally better.
Finally, the example shows the object’s function being called from inside an alert() function call. What do you think happens when this code is run? (Mouse over this paragraph to see.)
The alert function will put a message box in the middle of the screen. In this case, it will look like this:
Arrays
Arrays are programmer talk for lists of things. The “things” in an array can be numbers, strings, references to functions, references to objects, or even references to other arrays. We’re interested in them primarily because they can be used to hold lists of DOM objects. But first, here is a way to create an array of numbers:
var anArray = new Array(5, 10, 15, 20); anArray[10] = 25;
If this code reminds you of the way we created an object earlier, it’s because arrays are actually a special form of object, one that uses subscripts instead of names to select items in the array. The first line declares the variable named anArray, creates a new array, and fills the first four elements of the array with four numbers. The second line shows another way to add elements to an array: follow the name of the array with square brackets, and put a number between them to tell which element you want to assign a value to.
Open up the Firebug extension, (press F12 if the Firebug panel is not already showing), and type in the two lines above. Actually, you have to omit the var keyword from the first line because Firebug will create the variable for you automatically. What does Firebug display after you enter the first line?
[5,10,15,20]
Firebug is showing you a list of all the values in the array, separated by commas. After typing the second line, which assigns the value 25 to element number 10 of the array, type the name of the array and see what Firebug displays.
It will look sort of like this: [5,10,15,20,undefined,undefined,undefined,undefined,undefined,undefined,25]
The first four elements are the numbers that were put in the array when it was created, and the last one is the value that was added using the assignment statement. But what do all those “undefineds” mean? When you initialized the array, you supplied four values, which automatically went into the first four positions of the array. But when you added the value 25, you explicitly put it into position 10, skipping over six positions, which now show up as “undefined,” meaning they exist, but do not have values yet.
Before going further, count the number of values in the array. How many are there?
Eleven
Array subscripts are numbered starting with zero. So the first four elements of the array have subscript numbers 0, 1, 2, and 3. When you put a value into anArray[10], you were putting it into the position numbered ten, but that’s the eleventh position. (The position numbered zero is the first position.)
In addition to the elements of an array that you access using subscripts, every array object has a named element that tells how many elements are in the array. The name of this element is length. Use Firebug to show you the value of anArray.length; it should show you the number 11.
Experiment with arrays and subscripts: Put the string 'hello' into element number 8 and be sure you get the same value back when you refer to it. (Be sure you put quotes around the string.) How did this affect the length of the array? What does Firebug show if you type the name of the array now?
The length of the array didn’t change. That only happens when you add an element beyond the end of the array. So the array contents now show: the numbers 5, 10, 15, 20, four undefined values, the string “hello”, another undefined value, and the number 25.
Experiment some more by adding more elements, both numbers and strings, and put some of them both inside and beyond the end of the array. Verify that you can get back whatever you put into an array element, and that anArray.length always shows you the correct value. (For really large subscript numbers this might break down; feel free to experiment.)
One more point: just like regular variables, array elements can have their values changed by putting them on the left-hand side of an assignment statement. For example, which happens if you type this command into Firebug: anArray[1] = 'ten' ?
It changes the value of that array element from the number 10 to the string “ten.”
Loops
Arrays are useful because you can write a single piece of Javascript code that does the same thing to each element of an array instead of writing a separate piece of code to handle each item. For example, if you have the numbers 5, 10, 15, and 20 in the variables a, b, c, and d and want to know their sum (and don’t already know that it’s 50!), you could write something like: var sum = a + b + c + d;. But if those four values were in the first four elements of an array, you could use the following code to do the same thing:
var sum = 0; for (var i = 0; i < anArray.length; i++) { sum = sum + anArray[i]; }
There are two main kinds of loops in Javascript: for loops and while loops. As you might guess from looking at the code, this is a for loop, which works very well with arrays.
The second line of code controls the for loop. That line sets up the loop, and all the lines between the curly braces get executed repeatedly, once per loop iteration. The variable named i is the loop control variable. Before the first iteration, i gets assigned the value zero. Before each iteration (including the first) i is checked to see if it is less than the length of anArray ( i < anArray.length ), and if it is, the loop body is executed. At the end of each iteration, i is incremented by 1 ( i++ ), and the loop starts over.
In this example, the loop will be executed four times: the first time i will have the value 0, and anArray[0] will be added to sum. The second time i will have a value of 1, so anArray[1] will be added to sum. What value will be in sum at this point?
The variable sum will have the number 15 in it: the initial value assigned to it was 0, and at this point the numbers 5 and 10 will have been added to it.
Note that you will get an error if you try to add undefined or string values in your loop. There are ways to test whether a variable is a string, a number, or undefined, but we won’t look at that here.
When Code Runs
So far, we have been looking at isolated snippets of Javascript code. The natural question at this point is, “how does this code get run?” The simplistic answer is that the browser’s Javascript unit processes all Javascript statements as soon as the browser encounters them. But to understand that simplistic answer we need to cover the concepts of how and when Javascript code gets to the browser.
Script Tags
All Javascript code associated with a web page is either inside the web page itself or in a separate file. In either case, you use <script> tags to separate the Javascript code from the rest of the web page. Consider the following two <script> tags:
<script type="text/javascript"> var aVar = 3; </script> <script type="text/javascript" src="scripts/myscript.js" </script>
Both pieces of code could be put any place in a web page; either inside the <head> or the <body> sections of the document. The first example shows a Javascript statement inside the script element, and the second one shows how to refer to a separate file that contains Javascript code. In general, it is better to put all your Javascript code in a separate file because it helps organize your web pages better. But there is no difference between the two techniques as far as how the Javascript code gets processed. This tutorial shows code inside <script> tags to make the examples more self-contained.
Note that both <script> tags include a type attribute with a value of “text/javascript.” This is a required attribute (the page will not validate without it) that is used to tell the browser that the script statements are written in Javascript instead of some other scripting language. Note also that the second example seems to be a case where a self-closing script tag would make sense:
<script type="text/javascript" src="scripts/myscript.js" />
However, Internet Explorer (including IE7) ignores the script if you do not use a separate closing </script> tag.
Here is the sequence of what happens: the user clicks on a link or types a URL into the browser’s address bar, and the browser sends a request for a web page to a web server. The server sends a reply to the browser, which consists of the text of the web page requested by the user, possibly modified by one or more server-side scripts (PHP, for example). If the text of the web page includes any <img> or <script> tags, the browser makes additional requests to the server to obtain the image and/or script files. In the case of <script> tags without a src attribute, the browser gets the Javascript code from within the web page itself instead getting a separate file from the server. The browser may obtain any number of pieces of Javascript code from within <script> tags and/or external files, and it processes each piece of code as it encounters it.
“Processing a piece of code” means two different things: Statements that appear outside of any function definition are executed immediately, but function definitions are saved so they can be executed later.
<script type="text/javascript"> var a = 3; function fun () { var b = a + 4; alert(c + b); } var c = 5; </script>
Don’t attach too much significance to this block of code; it doesn’t do anything realistic. But it shows two variables being declared outside of any function definition ( a and c ), and another variable ( b ) being defined inside the function named fun() . The first and last statements will be executed by the browser’s Javascript processor as soon as it encounters them in the stream of information coming from the browser. But the definition of fun() will not be executed. Rather, this definition will be saved in the Javascript processor’s memory so that it can be executed at some later time.
Note that there is a reference to the variable named c inside the function, but that c doesn’t get defined until after the function definition. You cannot cannot use a variable before it has been defined and has an initial value assigned to it. But there is no problem in this example because fun() is not actually executed (it’s only defined) before the declaration and assignment of an initial value to c takes place. The question, then, is how to get a function to execute? To answer that, we have to look at events.
Events
There are two ways to get a function to execute. The first is to call it from another statement. If that statement is inside a function definition, we are left with the question of how the calling function got called. But if the call is outside of any function, the call takes place when the browser first comes to the statement that makes the call:
<script type="text/javascript"> function funny(arg1, arg2) { return arg1 + (arg1 * arg2); } var c = funny(3, 2); </script>
The first four lines of the script define the function funny(), and the fifth line immediately calls it, assigning an initial value of 9 to c .
The second way a function gets called is the more interesting one: the Javascript processor can be told to automatically call functions when events happen. Almost all the events we are interested in happen when the user does something: clicks on a link, clicks on a submit button for a form, mouses over a paragraph, changes the value of a text field, etc. But there is one event that is critically important and which has nothing to do with the user interacting with the web page. It’s called the onload event:
<script type="text/javascript"> function init() { alert('init was called'); } window.onload = init; alert('onload was set up'); </script>
You might find it easier to understand what is going on if you actually put this code in a web page and see what happens when you view the page. (Remember, <script> tags can go pretty much anywhere, but inside the <head> of the page is the “normal” place.)
The first thing to note is that the two alert() function calls will be executed in the opposite order from the sequence in which they appear. The second one appears outside any function definition, so it gets executed as soon as the browser get to it while reading in the web page. The first one gets executed when the init() function gets called, which is after the browser has gotten the entire web page from the server (including all images and script files), has completely built the DOM tree in memory, and has rendered the page in the browser window.
The key to all this is the window.onload=init; statement. When does this statement gets executed?
It is outside of any function definition, so it gets executed as soon as the browser encounters it. That is, before the web page has been completely read in by the browser, before the DOM tree has been built, and before the web page has been drawn on the screen.
What is window.onload?
Because of the dot in the middle, we know that window is an object (technically, it is a reference to an object), and onload is the name of a variable inside the window object.
If this point doesn’t make sense to you, you need to review the section on Objects earlier in this tutorial.
Look at the value being assigned to window.onload . If the right-hand side had said init(), the function init() would have been called, and the value it returned would have been assigned to window.onload. Since init() doesn’t return a value (there is no return statement in the function), this cannot be what is happening. Rather, the function name alone, without the parentheses, is a reference to the function, and that reference is what is getting saved in the window.onload variable. The usual way to talk about this sort of thing is to say that after the assignment, “window.onload points to the init() function.”
What happens is this: after the browser has built the DOM tree and rendered the page (i.e., after the page has “completely loaded”) the browser looks in the window object to see if the value of its onload variable has been assigned a value. If so, as is the case in this example, the browser calls the function pointed to by the variable. Our init() function gets called, and the second alert message pops up.
The window.onload variable is special because the browser automatically looks there to see if it has been initialized with the name of a function to be called.
What happens if the statement window.onload = init; is changed to window.xyz = init;?
Javascript will create a new variable named xyz in the window object and put the reference to init() in that variable. However, init() will never get called because the browser looks in window.onload rather than in window.xyz to see if there is a function to call.
You can also get the browser to call functions when the user causes events to happen. The kinds of events we are talking about involve using the mouse or keyboard to interact with the web page. For example, moving your mouse over the previous question caused the answer to appear after it. This was done by writing a Javascript function that knows how to cause a hidden paragraph to be displayed and connecting that function to the previous paragraph’s onmouseover variable.
Here are the names of some user events that can be defined for a node in the DOM tree: onmouseover (when the user moves the mouse over the element on the page), onmouseout (when the user moves the mouse away from the element), onclick (when the user points to an element on the page and clicks a mouse button - for Internet Explorer 6, the element has to be a <button>), onkeypress (when the user presses a key on the keyboard), onkeyrelease (when the user releases a key on the keyboard), onchange (when the user changes the value of an element, such as the state of a checkbox or radio button or the text in a text box). The list is longer than this, but you can see that just about anything the user might do with the mouse or keyboard can cause an event, and thus can cause a function to be called.
You might infer from some of the events listed in the previous paragraph that the function that gets called when an event happens might want to know more about the event than simply that it occurred. For example, if the user presses a key, which key was pressed? If the user clicked a mouse button, which one was clicked? Or, in the case of this tutorial, if the user moves the mouse over a paragraph, which paragraph? This sort of information is automatically passed to the function connected to the event in an object called an event object. Unfortunately, different browsers make the event object available to the function in different ways. Most browsers simply pass a reference to the event object as a parameter when the function is called. But Internet Explorer makes it available as a variable named window.event. If you look at the Javascript source code for this tutorial, one of the complexities you will see is the rather obscure code at the beginning of the event handling functions to figure out where the event object is.
Here is an experiment for you to try right now: this paragraph has an id attribute with a value of 'experiment'. Use Firebug to get a reference to it: x = document.getElementById('experiment'). Then connect my hideAnswer() function to its onmouseover variable: x.onmouseover = hideAnswer. Now move the mouse over the paragraph, and what happens?
This paragraph should now disappear when you move the mouse over the previous one.
If you want to be sophisticated, you can eliminate the variable x and just type:
document.getElementById.('experiment').onmouseover = hideAnswer
The code for this tutorial also includes a function named showAnswer(). You should be able to connect showAnswer() to the experiment paragraph’s onmouseout variable name to get the paragraph above to reappear when you move your mouse into and out of the experiment paragraph.
Events and Forms
In many cases, an easy way to connect a Javascript function to an event is to put some Javascript code in the xhtml tag you want to deal with. This approach is not ideal because it intermixes Javascript functionality with the xhtml structuring, the same way that it is not wise to intermix xhtml and css. Nevertheless, you are very likely to see this approach used to connect a function to the Submit button of a form:
<form method="get" action="http://babbage.cs.qc.edu/courses/cs081/Form_Script.sh"> <input type="password" id="pass" name="pass" /> <input type="submit" onclick="return verifyFormData()" /> </form>
This example assumes you defined a function named verifyFormData(), probably in an external file with the rest of your Javascript code for the page. When the user clicks on the Submit button, your function will be called. The key concept here (aside from the fact that the function gets called) is that the value returned by the function determines whether the form actually gets submitted or not. Note that the Javascript code connected to the onclick event must include the keyword return in order to pass the true or false value returned by the function back to the browser so it (the browser) can tell whether to actually submit the form to the server or not. If the function returns true, the browser will submit the form, but if the function returns false, the browser will not submit the form. For example, here is a version of verifyFormData() that checks a password typed by the user in a silly way:
function verifyFormData() { var passwd = document.getElementById('pass'); if ( passwd.value == 'secret' ) { alert('Right, \'secret\' is the password.'); return true; } else { alert('Wrong, \'' + passwd.value + '\' is not \'secret\'.'); return false; } }
You can try it here:
There is a lot to learn from that little example. The first thing to note is that the code inside the submit button is like a small function definition (but with no function name). That is why you have to put in a return statement to get the result of the verifyFormData() function (true or false) returned to the browser to control whether the form actually gets submitted or not.
The next thing to note is how the Javascript code gets a reference to the the password text box object by calling the document.getElementById() function. That function returns a reference to an Object that represents one node in the DOM tree. We will look at some of the functions that are available for working with the DOM tree below. For now, you should be able to understand that the parameter being passed to this function is a string representing the id attribute of the <input> tag we are interested in. The trick, then, is to know that you can get a copy of what the user typed into the password box by referring to the element’s variable named value. But that raises the next point ...
After the call to getElementById(), the verifyFormData() function uses an if statement to decide which value to return. The general form of an if statement is if (condition ) { true part } else { false part }. This tells Javascript to decide whether condition is true or false. If it is true, the statement(s) between the curly braces marked true part get executed. But if condition is false, the statements between the curly braces marked false part get executed instead. The else, the curly braces that follow it, and the entire false part can be left out if they are not needed. In this example, we used == to test if two strings are equal to each other. (That’s two equal signs right next to each other; using just one equal sign would make Javascript assign the value 'secret' to passwd.value, which is not what we want to do.) Other relational operators include != (not equal), < (less than, which used for comparing numbers), > (greater than), <= (less than or equal), and >= (greater than or equal).
The example also shows how you can put an apostrophe inside a string. Since an apostrophe would normally mark the end of the string, the special “escape character” (backslash, \) is used to tell Javascript that the next character is to be treated as part of the string, not as the apostrophe that ends it. As mentioned earlier, unlike many other languages, Javascript does not differentiate between single and double quotes so long as the type of quote used to start a string is the same as the type of quote used to end it. As a result, if you start a string with one type of quote, you can include the other kind inside it without using any backslashes. For example, the first alert() call could have been written:
alert("Right, 'secret' is the password.");
Unfortunately, although it works, making that change doesn’t make the message any less silly.
This way of connecting a Javascript function to an event, such as clicking on a button, is perfectly all right, and very commonly used. But just as we prefer to separate presentation (css) from content (xhtml), we also prefer separating dynamic effects (Javascript) from the xhtml of a web page. Doing so makes the code (both the xhtml and the Javascript) easier to read and understand. And it allows the possibility of easily reusing Javascript code in different web pages without having to copy it from one xhtml document to another. So, here is a better way to implement the same functionality as shown above:
First of all, we will use the same verifyFormData() function that we used above, but instead of putting it inside a <script> tag, we’ll move it to a separate Javascript file. If you look at the xhtml and Javascript code for this tutorial, you will see that the function definition has been set up that way.
Next, instead of connecting our function to the form’s Submit button, we will connect it to the form’s onsubmit property instead. This is just a somewhat more clear way of indicating what we want to do: we are saying to verify the form data whenever the user tries to submit the form rather than when the user clicks on the button that submits the form. This approach will now work even if there are two different Submit buttons in the form. (But if you are doing things like that, you don’t need this tutorial!) So we will remove the onclick from the Submit button, and add an id attribute to the <form> itself:
<form method="get" id="theForm" action="http://babbage.cs.qc.edu/courses/cs081/Form_Script.sh"> <input type="password" id="pass" name="pass" /> <input type="submit" /> </form>
Inside the separate Javascript file:
window.onload=init; function init() { document.getElementById('theForm').onsubmit = validateTheForm; }
If you look at the external Javascript file for this web page (javascript_tutorial.js) you will see this statement at the very end of the file.
One nice feature of this technique is that there is no need for an extra return statement the way there was when the Javascript code was inserted into the xhtml. The true or false value that is returned by validateFormData() directly controls whether the form gets submitted to the server or not.
Working With DOM Objects
You should be familiar with the idea the Document Object Model (DOM) is a way of representing web pages as a tree of nodes. The root of the tree represents the <html> element of the page, and the two children of that node represent the <head> and <body> elements.
Javascript provides many built-in objects and functions that let you write code that can examine and modify the DOM tree while the page is displayed, and to connect function to events associated with elements in the page. You have already used Firefox’s Firebug extension to examine some elements of the DOM tree, but to do so you had to be told what objects and variables to use. Another Firefox tool is the DOM Inspector, which you can invoke by typing Control-Shift-I on any web page. You can also get to it from the Tools menu. The DOM Inspector will not only let you view and modify the DOM tree (although less conveniently than the way Firebug does that), but will also tell you what variables and functions are associated with the objects in the DOM tree. Rather than search through gigantic books on Javascript, you can use the DOM Inspector to find out what your Javascript code has access to in the DOM tree.
To get to this information, start up the DOM Inspector, which will open up a new window. On the left is a tree view of the DOM tree itself, which you can expand and collapse and expand by clicking on the plus and minus boxes you will see there. As you select nodes in the tree, information about those nodes gets displayed on the right side of the window. The information on the right side comes from the xhtml code in the page itself, but there is a button next to the title on the right side that says “Object - DOM Node.” If you click on that button, you will see an option called “Javascript Object.< If you click on that option, the right side will become a view of all the properties of the DOM tree node that is selected on the left side as they can be seen by Javascript code. The root node of this property tree is called “Subject,” which represents whatever node of the DOM tree is selected in the left panel.
Start up the DOM Inspector now (so you are inspecting this web page) and open up the full tree in the left-hand panel. What is the id of the third <div> in the <body> of the document?
Looking at just the left-hand side of the DOM inspector, you should see that the third <div> has an id value of “content.”
At this point, the DOM Inspector gives much more information than you need or can use. But before you get rid of it, look over the property tree on the right side for some node in the DOM tree and take note of the following variable names: parentNode, childNodes, firstChild, lastChild, previousSibling, and nextSibling. These are all links to other nodes in the DOM tree (except childNodes, which is a list of links). They can be used to navigate from one node to its neighbors up, down, and sideways in the DOM tree.
The other thing you should look at in the right-hand panel are the attributes and style properties for whatever node you are looking at. If you open them up, you the attributes will list all the css information, and more, for the node you are inspecting. The style part will show you how you can change the CSS rules from within Javascript code.
There is more to add to this tutorial, but not for CS-081 for the Spring 2006 semester!
Glossary
- array
- A list of values. The elements in the list may be numbers, strings, or references to objects, among other things.
- assignment statement
- From left to right: a variable name, an equal sign (=), and an expression. The value of the expression becomes the new value of the variable on the left-hand side of the equal sign.
- comment
- Some descriptive text that is ignored by the Javascript interpreter.
- declare
- To use the var keyword to create a variable.
- event object
- An object that gets passed as a parameter to functions that respond to events. Variables in the event object give additional information about the event, such as the mouse position when the event occurred, what key was pressed, etc.
- execute
- To actually perform whatever operations a statement says to do.
- expression
- A way to represent or calculate a value. Variable names represent their values at the time the expression is evaluated, numbers represent their own values, and operators like +, -, *, and / can be used to calculate values of arbitrarily complicated expressions.
- function
- A set of statements that are grouped together.
- function call
- A statement or part of a statement that causes a function to execute.
- function definition
- A series of statements, starting with the keyword function, normally followed by the name of the function, then followed by a pair of parentheses, and a series of one of more statements inside curly braces. Defining a function does not execute it.
- interpreter
- The part of a web browser (or other application, such as Photoshop) that executes Javascript code.
- iterate
- To execute the statements in a loop body repeatedly.
- keyword
- A word in the Javascript language that is part of the language itself and cannot be used as a variable name. Examples are var and if.
- loop control variable
- A variable that changed its value for each iteration of a do loop.
- object
- A section of memory that can contain variables and references to functions.
- parameter
- A value that is passed to a function when it is called.
- reference
- A variable that has been assigned something other than a simple value like a number or string. Rather than put a copy of the entire function, object, or array that is being assigned to the variable, the interpreter puts a link to the actual function, object, or array. The link is called either a reference value or a pointer.
- relational operator
- Operators like ==, >, <=, and !=, which give results that are true or false.
- statement
- The smallest unit of execution in Javascript. Statements always end with a semicolon.
- string
- Characters inside quotation marks.
- subscript
- A number used to select an element in an array.
- value
- A number, string, boolean (true or false) that can be assigned to a variable.
- variable
- The Javascript name for a location in the computer’s memory.