Basic Commands and Language Structure


JavaScript is an object-based language. It accesses the browser and elements on the page in an object-oriented fashion. All the objects are stored in a hierarchy, and you can specify specific elements in the hierarchy using a dot-based notation that I'll explain in a bit.

Using this structure, all the elements of a single web page are contained within a base object container called window. Inside the window object is a set of smaller containers (or objects) that hold information about the various elements of a web page. The following are some of the main objects:

location

Contains information about the location of the current web document, including its URL and separate components such as the protocol, domain name, path, and port.

history

Holds a record of all the sites that a web browser has visited during the current session, and also gives you access to built-in functions that enable you to change the contents of the current window.

document

Contains the complete details of the current web page. This information includes all the forms, form elements, images, links, and anchors. It also provides many functions that enable you to programmatically alter the contents of items such as text boxes, radio buttons, and other form elements.


You can find a complete list of the available objects in JavaScript in Microsoft's JScript reference at http://msdn.microsoft.com, and in the Mozilla JavaScript documentation at http://developer.mozilla.org/en/docs/JavaScript.

Objects are accessed using a dot-based notation. To refer to a specific object, you need to locate it within the object hierarchy. For example, to refer to a form field called quantity in the first form on a page, you'd refer to it as document.forms[0].quantity. When multiple objects of the same type appear at the same location in a hierarchy, you have to refer to them by position in a list or by name. In this case, I'm referring to the first form on the document, so it's in the first position in the listthus, forms[0].JavaScript, like most programming languages, starts counting at zero.

Properties and Methods

Within each object container, you can access two main types of resources: properties and methods.

Properties are variables that hold a value associated with the object you're interested in. For example, within the document object is a property called title that contains the title of the current document as described by the <title> tag.

In JavaScript, you obtain the value of this property by using the command document.title. Properties are accessed using the dot notation I mentioned earlier. The item after the final dot is the property that you want to reference.

Some examples of properties that you can use include the following:

document.bgcolor

The color of the page's background

document.fgcolor

The color of the page's text

document.lastModified

The date the page was last modified

document.title

The title of the current web page

form.action

The URL of the CGI script to which the form will be submitted

location.hostname

The hostname of the current web page's URL


See the JavaScript documentation at http://developer.mozilla.org/en/docs/JavaScript for all the properties of each built-in object.

Methods are actions associated with a particular object. For example, the document object has a method called write associated with it that enables you to write text directly onto a web page. It takes the following form:

document.write("Hello world");


As was the case with properties, you execute, or call, a method by referencing the object that it's associated with, followed by a dot, and then the name of the method itself. Method names are followed by parentheses (()). The parentheses surround any arguments to that method. For example, if the method operates on numbers, the parentheses will contain those numbers. In the "Hello World" example, the write() method takes a string to write as an argument.

Note that even if a method accepts no arguments, you still have to include the parentheses. For example, the toString() method, which belongs to the location object, is used to convert the current document's URL into a string suitable for use with other methods such as document.write(). This method has no arguments. You just call it with empty parentheses, like this: location.toString(). The parentheses are necessary to distinguish between methods and properties.

As with properties, each object has a set of methods that you can use in your JavaScript scripts. The full list is at the same URL as the list of objects and properties mentioned earlier. Here are a few choice methods:

document.write(string)

Writes HTML or text to the current page. string is the text to write.

form.submit()

Submits the form.

window.alert(string)

Pops up an alert box. string is the message to display in the alert.

window.open(URL, name)

Opens a new browser window. URL is the URL of the page to open, and name is the window name for frame or link targets.


By combining the document.write() and location.toString() methods and the document.title property mentioned previously into an HTML document, you can create a simple JavaScript script such as the one shown here:

Input

<html> <head> <title>Test JavaScript</title> <script language="JavaScript"> <!-- hide from old browsers document.write(document.title + "<br />"); document.write(location.toString()); // done hiding --> </script> </head>  </html>


The results are shown in Figure 12.1.

Output

Figure 12.1. The results of your first JavaScript script.


Caution

Method, property, function, and variable names in JavaScript are all case sensitive. That is, uppercase and lowercase are different. If you're having problems getting the script for Figure 12.1 to work, make sure that you've written location.toString() and not location.tostring().


Events and JavaScript

Although implementing methods such as document.write() to create web pages might be useful, the real power behind JavaScript lies in its capability to respond to events.

As I mentioned earlier, events are actions that occur on a web page, normally when a visitor interacts with the page in some way. For example, when someone enters a value into a text box on a form or clicks a Submit button, a series of events is triggered inside the web browser. All these events can be intercepted by JavaScript programs.

Functions

Functions are similar to methods. The difference is that whereas methods are associated with built-in objects, functions are standalone routines that are embedded in the page. To define a function for the current web page, you would write something like this:

<script language="JavaScript"> function functionName(arguments) {  The actions to be performed by your function go here } </script>


In this code, functionName is just about any unique name that you choose, and arguments is a list of any values that you want to be sent to the function. The only function names you can't choose are those that are already part of JavaScript. Following the function definition and inside the set of braces ({}), you include the list of instructions that you want the function to perform. It could be a set of calculations, validation routines for a form, or just about anything else you can think of.

Note

JavaScript also includes a set of built-in objects and functions that enable you to perform mathematical operations, string manipulation, and date and time calculations. For a full list of built-in functions, refer to the online JavaScript documentation.


Functions are the core unit of reuse in JavaScript. If you want to do something more than once, you put the code to do it in a function, and then call the function wherever you want to do that thing. For example, let's say you had two values, a first name and a last name, and you wanted to turn them into one value. You could use the following code every time you wanted to do that:

fullName = firstName + " " + lastName;


Or you could write a function to take care of it, like this:

function makeFullName(firstName, lastName) {   return firstName + " " + lastName; }


The name of the function is makeFullName, and it has two arguments, firstName and lastName. It combines the two names using the + operator and returns the result. This code is pretty simple, and putting it in a function doesn't save much work. For more complex operations, creating a function makes more sense.

Later in this lesson, you'll learn how to include external JavaScript files on your page, much like you learned to link to external style sheets in Lesson 9, "Creating Layouts with CSS." You can put functions you commonly use in an external JavaScript file and link to that file from all of the pages that use the functions, saving yourself a lot of maintenance work if any of the functions need to be updated later on.

Assigning Functions to Events

After you define your functions, your next step is to assign them to the various events that you want to act on. You do so by assigning event handlers to the various elements of a web page or form. Currently, you can set the event handlers shown in Table 12.1.

Table 12.1. JavaScript Event Handlers

Event Handler

When It's Called

onblur

Whenever a visitor leaves a specified form field

onchange

Whenever a visitor changes the contents of a specified form field

onclick

Whenever a visitor clicks a specified element

onfocus

Whenever a visitor enters a specified form field

onload

Whenever a web page is loaded or reloaded

onmouseover

Whenever a visitor places the mouse cursor over a specified object

onselect

Whenever a visitor selects the contents of a specified field

onsubmit

Whenever a visitor submits a specified form

onunload

Whenever the current web page is changed


To specify functions that should be associated with any of these events, you just need to include the appropriate event handler as an attribute of the tag associated with that event. For example, consider a standard form with a couple of text fields and a Submit button, as shown here:

<form method="post" src="/books/2/631/1/html/2//cgi-bin/form"> <input type="text" name="username"> <input type="text" name="emailAddress"> <input type="submit"> </form>


Adding onsubmit="return checkform(this)" to the <form> tag causes the function called checkform() to be executed before the browser submits the form. In checkform(), you can perform any checks that you want and, if any problems occur, halt the form submission and ask the user to fix them. The this parameter inside the parentheses is used to tell the checkform() function which form object is associated with the <form> tag.

The Meaning of this

You might be a bit puzzled by the use of this as an argument passed to a function. Here, this is shorthand for the current object. When you're using an event handler in a tag, this refers to the object represented by that tag. In the previous example, it refers to the form associated with the <form> tag in which it appears. Why use an argument at all? So that one function can be used with many objects. In this case, we might have four forms on the page that can all be validated using checkform(); we can distinguish between those forms by passing a reference to the form using this.


In addition, you can do field-by-field checking by including either onchange or onblur event handlers in each <input> tag. Because the onblur handler is called each time a person leaves a field, it's ideal for input validation.

Buttons such as the Submit button trigger the onclick event. For example, <input type="submit" onclick="processclick()"> calls the function processclick() whenever the Submit button is clicked.

Variables

In addition to properties, JavaScript also enables you to assign or retrieve values from variables. A variable is a user-defined container that can hold a number, some text, or an object. But unlike most high-level languages that force you to limit the contents of each variable to a specific type, JavaScript is a loosely typed language. This means that you don't need to specify the type of information that a variable can contain when you create it. In fact, data of different types can be assigned to the same variable, depending on your requirements.

To declare a variable for a JavaScript program, you would write the following:

var variablename = value ;


In this form, variablename is a name that you choose. You can choose any name you like, as long as it's not already reserved as part of the JavaScript language. The equal sign (=) following the variablename is called an assignment operator. It tells JavaScript to assign whatever is on the right side of the = signvalueas the contents of the variable. This value can be a text string, a number, a property, the results of a function, an array, a date, or even another variable. Here's an example:

var name = "Laura Lemay"; var age = 28; var title = document.title; var documenturl = location.toString();var myarray = new Array(10); var todaysdate = new Date(); var myname = anothername;


Note

Variable names (and function names) can consist of the letters a through z, the numbers 0 through 9, and the underscore (_) symbol. A variable name cannot start with a number.


Tip

If you declare a variable inside a function, you can access the contents of that variable only from inside the function itself. This is said to be the scope of the variable. On the other hand, if you declare a variable inside a <script> block outside your functions, you can access the contents of that variable from any JavaScript code on the web page. This is referred to as global scope.


Operators and Expressions

After you define a variable, you can work with its contents or alter them using operators. Table 12.2 lists some of the more popular operators provided by JavaScript and examples of each. (As before, for a full list of all the supported operators, refer to the online JavaScript documentation.)

Table 12.2. JavaScript Operators and Expressions

Operator

Example

Description

+

a = b + c

Adds variables b and c and assigns the result to variable a.

-

a = b - c

Subtracts the value of variable c from variable b and assigns the result to variable a.

*

a = b * c

Multiplies variable b by variable c and assigns the result to variable a.

/

a = b / c

Divides variable b by variable c and assigns the result to variable a.

%

a = b % c

Obtains the modulus of variable b when it's divided by variable c, and assigns the result to variable a. (Note: A modulus is a function that returns the remainder.)

++

a = ++b

Increments variable b by 1 and assigns the result to variable a.

--

a = --b

Decrements variable b by 1 and assigns the result to variable a.


Note

The examples shown in the second column of Table 12.2 are called expressions. An expression is any valid set of variables, operators, and other expressions that evaluate to a single value. For example, b + c evaluates to a single value, which is assigned to a.


You also can use a special set of operators, called assignment operators, that combine the assignment function (=) and an operator into a single function. Table 12.3 lists the assignment operators provided by JavaScript.

Table 12.3. JavaScript Assignment Operators

Assignment Operator

Example

Description

+=

a += b

This example is equivalent to the statement a = a + b.

-=

a -= b

This example is equivalent to the statement a = a - b.

*=

a *= b

This example is equivalent to the statement a = a * b.

/=

a /= b

This example is equivalent to the statement a = a / b.

/=

a %= b

This example is equivalent to the statement a = a % b.


Note

The + and += operators can be used with string variables as well as numeric variables. When you use them with strings, the result of a = "text" + " and more text" is a variable containing "text and more text".





Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day
Sams Teach Yourself Web Publishing with HTML and CSS in One Hour a Day (5th Edition)
ISBN: 0672328860
EAN: 2147483647
Year: 2007
Pages: 305

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net