A JavaScript Primer

Here are the very basic components of JavaScript and their purpose.


Variables

Variables are used to temporarily store information. To create a variable, use the keyword var, then declare the name, and optionally the initial value. Variable names cannot begin with a number or contain any spaces or special characters except an underscore.
var variableName = initialValue

For example

var music = "Rock and Roll"
var opinion

Note that the initial value of opinion is undefined. The intent may be to have its value set by user input later on.


Objects

Objects are any item in a document like images, form fields and hyperlinks. In addition, the browser window itself is an object. Some JavaScript objects that reflect physical HTML elements are Image(), Anchor() and Link(). JavaScript comes with many built-in objects as well, abstract objects used only in scripts like String(), Number(), Date(), Math(). The complete list of available JavaScript objects are here.

Variables are also objects once they are given a value. The type of object is determined by the data type, or nature of its value. In our first variable example the value of music was set to "Rock and Roll", which is a string of text. So the variable music is a String()object. A variable name is just a label for an object.

To create an object, use the keyword new, then define the name and any parameters or characteristics the object has. Note that object names are capitalized, the keyword new is lowercase.
new Object(arguments)

So if you were doing script that counted the days until Christmas, you would need to create new date set to Dec. 25, like this

var xmas = new Date("December 25, 1998")

Note that you need a variable name as a label to refer to the object in your script. The very first variable example is actually the same as doing this:

var music = new String("Rock and Roll")

Tip: As a shortcut, any time a text value is in quotes, JavaScript automatically assumes you are creating a literal string of text and allows you to leave out the new String() constructor, as in the very first variable example. The Number() object works the same way. JavaScript assumes any number not in quotes is a Number() object. A date, however, is not always so obvious. It could be a set of numbers and slashes, or words and numbers. You have to tell JavaScript you are creating a new Date().

The difference between the types of objects is seen in how JavaScript handles them. In JavaScript

10 + 10 = 20
"10" + "10" = "1010"
"10" + 10 = "1010"

Properties

Every object in a page has properties, which are its specific characteristics. Everything from script functions to form fields count as objects and retain certain properties. Each object is also a property of its parent in a hierarchy of document objects. This is commonly referred to as the document object model. In scripting, this hierarchy is written
parentObject.childObject.property

For example, the value of an email field, on a form, in a web page, in a browser, might be referred to as

window.document.formName.emailField.value

The value is a property of the emailField. The emailField is a property of formName. formName is a property of the document. The document is a property of the browser window. That is the document object model.

To see what properties are available for each document object, go here.


Arrays

An array is a series of objects or values stored under one name. Each value contained in an array can be retrieved individually by referring to it's index location in the array. The index can be an integer or a name in the form of a string of text. All numerical array indices begin at 0.
arrayName[indexInteger]
arrayName["indexName"]

For example, when an HTML document is a frameset, it has an array of frames. The first frame is window.frames[0] and the second is window.frames[1]. (Remember, array indices start at 0.)

An HTML document can also have more than one form. It can have an array of forms. You can refer to the first form on your page as

document.forms[0]
If the form has a NAME="Loan-App" attribute in the FORM tag, you can refer to the form as
document.forms["Loan-App"]

If the name of the form did not have a hyphen, you could refer to the form more directly by its name alone: document.LoanApp.

However, when a hyphen is used in a form name like document.Loan-App, the script interprets this as subtraction, like document.Loan minus App. Therefore, you must use the array method of referring to the form in this case, where the name is in quotes.


Functions

For every object on a page, it can have at least one activity it can do. A function. You define what that activity is when you define a script function. Use the keyword function, then define the function name, then a pair of parenthesis to enclose any arguments allowed, then the function itself is defined within braces.

Arguments are options you can pass to the function if needed. For example, if your function changes the background color, you may need to pass the hex code you want to change to as an argument. Not all functions need to take arguments.

Here is a function defined on a single line
function functionName(arguments) {function definition}

Here is a function defined on several lines
function functionName(arguments) {
    // a single-line comment
    function definition statement line one;
    function definition statement line two;
    function definition statement line three;
    /* This is a multiple line 
    comment.  It continues until
    it reaches a closing comment 
    mark like this. */
}

A semi-colon is like a line break. It closes a statement. So if a function definition has two statements, but written on one line, it must have semi-colons to differentiate the two statements. Like this:
function fName(args) {statement one;statement two}

For example, here is a function that simply sends the user back one page in their browser history. When called from a hyperlink, it will send the user to the previous page they were on, even if it was not on your site.

The source code

<SCRIPT>
function goBack() {
    window.history.back();
}
</SCRIPT>

<A HREF="javascript:goBack()">Go Back</A>
<!-- HREF and SRC require a protocol: --
  -- to call a JavaScript function,   --
  -- use the javascript: protocol     -->

See it in action
Go Back


Event Handlers

You can give the object on the page the ability to execute a function through its event handler. Like the onclick event or the onmouseover event.
<TAG ATTIBUTE="something" eventHandler="function()">

So if you had a function that changed the background color, and wanted to trigger it when a form button is clicked, it would be written like this:

<INPUT TYPE="button" VALUE="Change" onClick="changeBackground()">

More on events and event handlers available here.


See it in action

Here is a script that changes the background color based on which form button is clicked.

The source code (see if you recognise all the elements as described above)

<SCRIPT LANGUAGE="JavaScript">
<!--
function changeBackground(color) {
    var hexCode = changeBackground.arguments[0];
    document.bgColor = hexCode;
}
// -->
</SCRIPT>

<FORM>
<INPUT TYPE="button" VALUE="Blue" onClick="changeBackground('99CCFF')">
<INPUT TYPE="button" VALUE="White" onClick="changeBackground('FFFFFF')">
</FORM>

Note the single quotes around the hex code arguments being passed to changeBackground(). This is because using double-quotes would close the onClick="changeBackground(" before the hex numbers. Single-quoting allows you to nest a quoted string inside a quoted string!

On to part two...