introduction | values and variables | expressions and operators | statements | functions | objects | events

QUICK TUTORIAL - JAVASCRIPT BASICS - Overview

Programming with JavaScript

JavaScript is a lightweight, interpreted programming language, developed by Brendan Eich for Netscape in 1995. Netscape had made a marketing arrangement with Sun Microsystems, and wanted to give web developers an easier way to interact with Sun’s Java programming language. The new language was a loosely-typed scripting language, designed to help web developers tie into web page elements (like forms and images) without having to learn object-oriented software design or use a compiler. It was called “LiveScript.”(Champeon, 2001)

JavaScript vs Java
In an unfortunate naming incident, LiveScript was renamed JavaScript in order to let some of Java’s popularity rub off on the new language. Ever since then, countless people have had to say, over and over again, “No, JavaScript and Java are not the same thing at all.” Other than some very basic programming syntax (if statements, while loops etc.), which JavaScript shares with C, C++ and Java (among others), it’s a very different animal. One major difference is that variables in JavaScript do not have to have a declared data type. In many ways, it resembles Perl, another interpreted language. (Flanagan, 2002, p,1)

The Three Parts of Client-Site Web Programming
It will probably help you to understand JavaScript if you realize that part of what you will learn is the programming language, part is the Document Object Model (the DOM), which is defined by the browser, and part is the ability of the operating system to sense user inputs (through the keyboard and mouse etc.) and announce them to the application as "events."

W3C DOM Standards Replace the Browser Wars
One of the exciting developments of the last few years is the growing acceptance of a set of standards for the DOM put out by the World Wide Web Constortium (the W3C). Until the major browser manufacturers decided to cooperate more, developers were faced with a bewildering array of different definitions of just what the document objects were, what were called, and how they behaved, making it impossible to write client-side applications of any complexity without having to serve up different versions of the program for each browser (or browser version!!). The latest generation of browsers (Internet Explorer 6, Mozilla 1, Opera 7, Safari 1) gives hope that there is enough agreement to allow client-side applications to begin to flourish again.

However, there are enough people hanging on to older browsers (notably Netscape 4.7), that developers still have to create separate versions of their sites if they don’t want to have to ignore that segment of users. (Why Netscape 4.7? Because it was the last browser the “little guys” at Netscape made before being swallowed, Jonah-like, by the AOL whale. Like Jonah, it also got spit out again – people from the old Netscape browser crowd formed Mozilla when AOL laid them all off in 2003.) This is not all bad, however. It is generally good practice to make a text-only version of your web pages available for display on wireless devices, assistive devices for the handicapped, and people with low-bandwidth access to the Internet. People with older browsers may also have slow dial-up connections, and they’ve long ago turned off images and javascript. Creating a single, text-only version of your site may serve many more people than just the Netscape 4.7 crowd.

Let us now examine just what you can do with the DOM using JavaScript. We’ll start from the outside and work in – things you can do with the browser window itself, things you can do with the web page, and finally, ways you can interact directly with the user.

Things you can do with the browser window using the methods of the window:

The browser essentially opens an API (Application Programming Interface) to the language by defining all of the HTML, text, image and multimedia elements on the page as objects that can be manipulated by the language. The objects have methods, which are actions the object can take (e.g., document.write), and properties, which are something like HTML attributes (e.g., document.image.width) but which are also its sub-objects, known as its child objects. For example, a checkbox is an object, but a checkbox is also a property of a form object, which itself is a property of a document object. (e.g., document.form.checkbox.value)

  1. Open a page in a new browser instance or popup window

    window.open(”extrainfo.htm”,”infowindow”,”scrollbars,width=300, height=200,resizable,left=20,top=30”)
  2. Send the user back to a previous page (simulates the back button).

    window.history.back()

    The following will send the user back two pages (useful if you have a “thankyou” page following a forms submission, and you want to take your visitor back to the page they were on before they filled out the form.

    window.history.go(-2)
  3. Display a message

    window.alert(“Thank You!”)

    This can be shortened (and usually is) to

    alert(“Thank You”)

Things you can do with the web page using the methods of the document:

  1. You can write things to the page

    document.write(“Hello, world!”)
  2. You can generate new HTML code

    document.write(“<tr><td>Here’s a new row.</td></tr>”)
  3. You can help the server remember the “state” of the document by setting cookies.

    document.cookie = “FP1564 size 12; expires=Thu, 2 Aug 2005 20:47:11”

    HTTP is a “stateless” protocol, that is, the server does not keep itself connected to your computer even during a single session. As soon as it has fullfilled your request for a web page or other resource, it drops the connection with you, and does not remember your session or where you left off the next time you hit it with a request. In order to remember, say, that you ordered the pink and orange sweater (FP1564) the server will store the information it needs for later use in a small text file called a cookie.

Ways to interact with users using events and event handlers

As Peter-Paul Koch (www.quirksmode.com) put it, “events and event-handling are the beating heart of JavaScript.” The DOM defines a set of ways to interact with it through the keyboard or the mouse called “events” (e.g., mouseover, keypress, focus) and a companion set of “event handlers” for those events (onMouseover, onKeypress, onFocus) is a part of JavaScript. Using Javascript and the DOM, your web page can react to user input in some interesting and useful ways. Many of the interactions uncovered by clever programmers have not yet found practical application, but some have, most notably the swapping of images on a “mouseover” and various kinds of form handling.

  1. mouseovers – you can use Javascript and the DOM to change the URL of an image in response to a user rolling the cursor over the part of the screen where the image is located. You can then cause the URL to be changed back when the curser leaves the boundaries of the image. Making an image change when the user mouses over it has been used for years now to signal that you’re in the right spot to click on a button.
  2. calculations – you can cause a value in a form element to change based on user input in another form element, for example, putting the total cost in a box after a user has ordered several items for purchase from your online store.
  3. Form validation – as your user moves through a form, filling in the blanks, a JavaScript program can evaluate the input and determine if it is at least superficially valid, saving a round-trip to the server just to correct trivial input errors.
  4. Preprocessing of data – if an application requires some massaging of the data before it is used, JavaScript could perform some of that preprocessing on the client machine, reducing the amount of data that must be transmitted to the server
  5. Triggering activity when your user arrives or leaves the page – When a user requests a page, the “onLoad” event handler can be invoked to preload images, or place the cursor at a particular place, or open an other browser window with an advertisement (even open that window in such a way that it is placed behind the current window, so you don’t see it until you close the browser. The “onUnload” event handler can be invoked when you go to another page, or close your browser, to open up another browser window, or several others – one last chance to get an advertisement in front of your eyes at least for the length of time it takes you to close the window.
  6. Triggering activity when your user selects or unselects an element on your page – When the cursor is placed in an element, say, a form’s text box, that (selected) element is said to have “focus.” When the user puts the cursor somewhere else, the element now has “blur.” Imagine that your user has just entered in the number “3” in the “quantity ordered” field. As the user tabs out of the “3” box, the “onBlur” event handler invokes a JavaScript program which calculates the total cost including shipping and tax and enters that amount into the “Total Cost” field.

The actual “programming” part of JavaScript:

JavaScript shares some fundamental programming concepts with other programming languages, such as the following:

Statements (these are JavaScript "sentences")

Setting conditions for actions:

if (condition) {do something}

Example:

if (year<2004) {

alert(“Please enter valid expiration date.”)

}

Giving alternatives for different conditions:

if (condition) {do something}

else if (other condition) {do something else}

else {do some other thing}

Example:

if (year<2004) {

alert(“Please enter valid expiration year.”)

}

else if (year==2004) {

alert(“Thank you. Now please enter expiration month.”)

}

else {

alert(“Thank you for your order.”)

}

Continuing an action a specified number of times

for (initial condition, test for end, go to next) {do something}

Example:

Continuing an action under specified conditions

while (condition is satisfied) {do something}

Example

Using Variables to hold values

A variable is a kind of bucket you create to hold things for you while you manipulate them. They can hold just about any kind of data: number or text values, objects, even the little programs called functions.

JavaScript has a very limited set of native data types (number, string, Boolean, and null) but contains in the language the ability to create objects that hold very specific types of data, like Dates, or Rectangles, or Currency, or MuscleCars.

Example: var x = 3
//This can be read as "Let x be 3"

var today = new Date()
//This is how you create a Date object in JavaScript

Unlike some other programming languages, you do not have to “declare” variables as specific data types before you use them, although you may. “Declaring” a variable is simply listing it, though sometimes you may want also to set its initial value when you list it.

If you declare a variable in a document outside any function you write, it becomes a “global” variable, usable anywhere on your page. If it gets defined inside a function, it is a “local” variable. A local variable of the same name as a global variable will overwrite the value of the global variable.

Expressions

An expression is a phrase of Javascript that the JavaScript Interpreter can evaluate to produce a value

Example: .6 //a numeric literal

“Hello World” //a string literal

true //a Boolean literal

null //the literal null value

function(x){return x*x} //a function literal

Operators

Two or more expressions can be combined using operators, and JavaScript will return a result based on the meaning of the operator. An operator (among other things) can do math (6+12), make comparisons (c<d), or apply Boolean logic (a && b). Here is a partial list of operators:

Operators (Arithmetic)

+, -, *, /

Unary minus (-)

Unary plus (+)

Increment (++)

Decrement (- -)

Operators (Equality)

Equality (= =)

Identity (= = =)

Not Equal (! =)

Not Identical (! = =)

Operators (Comparison) <, <=, >, >=

Operator (String Concatenation) “These are the times” + “ that try men’s souls.”

(becomes “ These are the times that try men’s souls.”)

Operators (Logical) AND (&&)

OR (||)

NOT (!)

Arrays

An Array is an indexed collection of objects. What this means is that, once something is contained in an array, you can refer to it by its “index,” or position in the array.

  • The DOM defines all of the elements on the page as belonging to arrays. Instead of referring to an element by its “name” (which you must supply to the element) you could refer to it by its “number,” or position in the document. Array numbering starts with the number “0” instead of “1” so the 3rd image on the page would be document.image[2].
  • JavaScript also contains some pre-defined arrays. For example, there is an array called “Month” which is a collection of all of the months of the year, in order from January to December. Because all arrays in JavaScript are numbered starting with “0” January is month[0] and February is month[1].
  • You can also create your own sets of arrays. Here’s an example:

    var x = new Array(foo, bar, flim, flam, floozle)

    What is x[2]? If you said “flim” you got it!

The Fun Part – Writing Functions

A function is a little program, something like a subroutine. Once you write it, you can call it whenever you need it on your page just by invoking its name.

The general format for a function is this:

function functionname([argument [arg2 […argn]]]) {

statements}

Example (standard mouseover function):

function togglepic(imgName,imgURL){

document.images[imgName].src = imgURL;

}

In this function, the name of the function is “togglepic”, the arguments are imgName and imgURL . The statement uses the assignment operator (=) to reassign the source of the image to a new source. In the place on your page where you want to make an image swap, you say this:

<a href=”javascript:void(0)” onMouseover=”togglepic(‘picture1’, ‘buttonglow.gif’)” onMouseout=”togglepic(‘picture1’,’button.gif’)”><img src=”button.gif” name=”picture1”></a>

Here an event handler (onMouseover) invokes the function togglepic, causing buttonglow.gif to replace button.gif in this spot as long as the cursor is over the image. When the cursor leaves the spot (onMouseout), a second invocation of the function togglepic causes the image to revert back to “button.gif.”


References

Champeon, S (2001) JavaScript: How did we get here? (http://www.oreillynet.com/pub/a/javascript/2001/04/06/is_history.html)

Flanagan, D. (2002) JavaScript: The definitive guide Sebastopol, CA: O’Reilly Media, Inc.

Koch, P (2004) Introduction to Events Quirksmode (http://www.Quirksmode.com)

http://devedge.netscape.com/