JavaScript Basics

Definitions

JavaScript is an object-oriented programming language designed for the world wide web. JavaScript code is integrated directly into common HTML documents and is interpreted by the web browser when the document is loaded. JavaScript allows web developers to include high levels of interactivity in web pages. The following definitions must be understood to begin to create interactivity with JavaScript.


Objects

An object is any definable thing. A car is one example of an object in the physical world. A car may contain other objects like the trunk. In turn the trunk may contain other objects like the spare tire. In JavaScript the hierarchy of objects is represented in code using "dot syntax". For example, if we were to use dot syntax to represent a spare tire in the physical world we might refer to it as:


car.trunk.sparetire

In JavaScript the web browser window and the currently loaded document are examples of common objects. The window contains the document which may contain other objects like images, forms, buttons, and links. The specific way a web browser deals with its hierarchy of objects is called the Document Object Model (DOM). The W3C is in the process of creating a standard DOM. Until that happens, webmasters must spend time dealing with the inconsistencies between the DOMs of the two major browsers. In the JavaScript language every object can be given a name and referred to in code using dot syntax such as:


window.document.myphoto


The above code would refer to an image named "myphoto" residing in a document loaded into a web browser window.

Think of objects as the nouns in the JavaScript language.



Instance

An instance is one particular incarnation of an object. For example, a car is an object and a Plymouth Sundance is one instance of the car object. The photograph above is an instance of the image object.


Properties

In real life objects may also have properties. A car object may have a property known as "color". That property would be referred to as:


car.color

Similarly, in the JavaScript language, each object may have many properties associated with it. For example the document object has a property called "bgColor" which represents the background color.


window.document.bgColor




Values

In real life properties have values. A car object may have a property known as "color" with a value known as "blue". If the owner chooses to paint the car a different color then he/she would be assigning a new value to the color property. The following code would assign the value of "red" to the property "color" of the object "car". Notice that JavaScript code statements end with a semicolon.


car.color=red;

JavaScript objects also have properties which may be assigned values. For example the document object has a property called "bgColor" which represents the background color and may be assigned a value such as "silver".


window.document.bgColor="silver";

JavaScript is often used to create rollover graphics where the image changes as the mouse is moved on top of an image. This technique relies on the src property of the image object in JavaScript. The src property has a value to indicate the location of a graphic file on the hard drive of the web server.

The image below of my head is created using a standard HTML tag called IMG. One of the attributes of the tag is the NAME attribute. In this example the NAME attribute has a value of "estrella". Here is the HTML code.

<img src="estrellaheadnobeard.jpg" width="124" height="169" border=0 name="estrella">

Because the image object is named, it can now be referred to in JavaScript code.

Move the mouse over the image below to see the relevant code.

 


Variables

In real life, we deal with variables all the time. At a bar, several patrons may order "the usual". The bartender, being familiar with each patron, assigns the value "gin and tonic" to the variable "the usual" for one patron and assigns the value "margarita" to the variable "the usual" for another patron. Similarly, a variable named "myFavoriteColor" may be assigned different values. The code below illustrates the creation and use of a variable to assign the color "teal" to the car object.


var myFavoriteColor = "teal";
car.color=myFavoriteColor;

Similarly, in JavaScript, the value for a property like bgColor can be placed in a variable.


var myBackgroundColor = "silver";
window.document.bgColor=myBackgroundColor;

Valid named colors for web pages are white, black, green, maroon, olive, navy, purple, gray, red, yellow, blue, teal, lime, aqua, fuchsia, and silver.

Type a color here then click the button below:

 

Arrays

An array is an ordered collection of data. Each element of an array is a variable which can hold data of any type. Generally an array is used to hold related data. A particularly intuitive example is an array to represent the spices in a spice rack in your kitchen.

 

Var spicerack = new Array();
spicerack[0] = "cinnamon";
spicerack[1] = "salt";
spicerack[2] = "pepper";
spicerack[3] = "cumin";
spicerack[4] = "oregano";

 

The numbering of arrays always begins at 0 but programmers sometimes do not populate the [0] element so that numbering can begin more naturally at 1. The value of any element in the array can be changed through simple assignment.

spicerack[4] = "garlic";

 

Very often in programming a 'for' loop is used to populate an array with values. For example, the form below requests information about a user's favorite spices. The information is stored in an array using a simple 'for' loop.

Please type in your four favorite spices.

First Choice
spicerack[1]
Second Choice
spicerack[2]
Third Choice
spicerack[3]
Fourth Choice
spicerack[4]

Now click the button below to see your choices displayed in the fields below.
View the code of this page to see how the loop works.
The code uses a loop that exploits the fact that the four input fields above are named with consecutive numbers (spicechoice1, spicechoice2, spicechoice3, spicechoice4).

First Choice
spicerack[1]
Second Choice
spicerack[2]
Third Choice
spicerack[3]
Fourth Choice
spicerack[4]

 

 

Methods

In real life, objects sometimes take actions. A "car" object might take an action called "brake". The "brake" action has been designed by the car manufacturer to slow the car down. Methods take values. For example, the "brake" method could take values of "fast" or "slow" depending on how much force the driver applied to the pedal. In JavaScript the term "method" is used to describe the actions that objects take and parentheses are used to contain the values. In this example the "brake" method would be expressed in dot syntax as follows:


car.brake("fast");
car.brake("slow");


Similarly, JavaScript objects have many methods. One of the simplest methods is the write() method of the document object. This method is used to write text to the current document as the page loads.


window.document.write("Greetings JavaScript Students");

Think of methods as the verbs in the JavaScript language.

Build a page with document.write()

Type any text below, then click the Show My Page button to see a new web page with your text.

 




Events and Event Handlers

In real life, objects sometimes encounter events. A "car" object might encounter the "blowout" event and lose a tire. The driver must handle this event by performing an action (i.e. method) such as applying the brake to stop the car. In JavaScript the term "event handler" is used to describe the code that responds to events initiated by visitors to a web page. In this example the "blowout" event is handled by the "onBlowOut" handler which responds to the event by initiating the brake() method.:


onBlowOut="car.brake('fast')";

Event handlers may also respond to an event by changing the value of a property. In this case the shape property of the tire object is assigned the value of "flat".


onBlowOut="car.tire.shape='flat'";

Similarly, JavaScript objects encounter many events. One of the most common events is the "mouseover" event which is triggered when a visitor to a web page moves the mouse on top of an object programmed with an "onMouseOver" handler. In this example, a simple link is coded with the onMouseOver handler to change the background color of the page to silver when the visitor moves the mouse over the link.


<A HREF="#" onMouseOver="document.bgColor='silver';">
Move mouse here to change background to silver.</A>

Demonstration

The links below illustrate one use of the "document" object with "event handlers". The document object is one of the most fundamental objects in the JavaScript language and it has many properties. One such property is called bgColor for background color.

The value of bgColor can be changed in many ways through JavaScript. In the example below, each link has been altered with the addition of an event handler called "onMouseOver". When the user moves the mouse over the link, the event handler assigns a new color to the bgColor property of the document object. View the source code of this page to observe how the value for the bgColor property is changed.


Move mouse here to change background to yellow.

Move mouse here to change background to red.

Move mouse here to change background to silver.

Move mouse here to change background to white.



Assignment Operators

A value can be assigned to a variable using a simple assignment operator like the equal sign ("=").

var myAge = 37;
var myName = "Steven";

More complex operators may be used to alter the value once it is assigned.

var myAge = 37;
myAge += 4; is the same as myAge = myAge + 4; Result is 41.
myAge -= 4; is the same as myAge = myAge - 4; Result is 33.
myAge *= 4; is the same as myAge = myAge * 4; Result is 148.
myAge /= 4; is the same as myAge = myAge / 4; Result is 9.25.

For text values the addition operator concatenates (joins) text strings together.

var myName = "Steven ";
myName += "Estrella"; result is "Steven Estrella"

Comparison Operators

Comparison operators allow values to be compared. The equivalency operator is expressed as two equal signs ("=="). One of the most common programming errors in JavaScript and other languages is the use of the assignment operator ("=") when the equivalency operator ("==") is desired. Statements using comparison operators always result in Boolean values (TRUE or FALSE). "AND" statements comparing two expressions are TRUE if the expressions on both sides of the comparison operator are TRUE. "OR" statements comparing two expressions are TRUE if either expression is TRUE.

37 == 30 + 7; This statement returns a value of TRUE
37 != 25 + 7; This statement returns a value of TRUE
37 > 27; This statement returns a value of TRUE
37 >= 37; This statement returns a value of TRUE
37 <= 36; This statement returns a value of FALSE
(15 == 10+5) && (33 == 28 + 3); This "AND" statement returns a value of FALSE
(15 == 10+5) || (33 == 28 + 3); This "OR" statement returns a value of TRUE
"Steven" == "Gill"; This statement returns a value of False
"Steven" != "Gill"; This statement returns a value of TRUE


Functions

A function is a group of JavaScript statements that perform a designated task. Functions are often stored in the HEAD section of an HTML document and do their work when invoked (i.e. 'called') by other JavaScript statements. A function has the structure below. Curly brackets are used to contain the statements of the function.

function doSomething(){
alert("What do you want me to do, " + document.sampleform.username.value + "?");
}

Here is a simple example. The form below asks the user to type in a name. When the button is clicked, the 'doSomething' function is called and an alert box containing the user's name is displayed.

Please type your name:


 

Document Object Model

A scriptable web browser, like Netscape Communicator or Microsoft Internet Explorer, creates an internal roadmap of all objects found on a web page. The roadmap or Document Object Model (DOM) is a hierarchy with the browser window at the top of the hierarchy. The document object is one level below the window object. Any scriptable objects within the document, such as forms, may also have subordinate objects. For example, the text field in the previous section is an INPUT object of type TEXT and is called "username". The "username" object is part of a FORM object called "sampleform" which in turn is part of the current document and window. The DOM used by Netscape 4.x browsers requires web designers to specify the complete path to any object they wish to manipulate in scripting. Hence, a line of JavaScript code such as the one below can be used to alter the value attribute of the username form.

window.document.sampleform.username.value = "Some text goes here";

In practice the reference to the current window can be assumed so designers more often will simply type:

document.sampleform.username.value = "Some text goes here";

 

One of the principal differences between the DOMs of Netscape and Microsoft is the use of the ALL keyword in Microsoft's Internet Explorer. Any uniquely named object can be referenced in Internet Explorer DOM using the following structure:

document.all.someobjectID

 

This works for SPAN and DIV tags or any other object with a unique ID attribute. The use of the ALL keyword means that creating references to deeply nested objects in Internet Explorer is simpler than in Netscape Communicator.

It is necessary to understand many details of the two DOM implementations to script changes to object position and visibility that take place after the page has loaded. For a very complete reference, see Danny Goodman's book Dynamic HTML: The Definitive Reference, published by O'Reilly in 1998.




Go On To Programming Basics