A Crash Course in JavaScript


This section will introduce you as quickly as possible to JavaScript. If you're already familiar with the language, you can skip this section for now, though the tables in this section may come in handy later as a kind of quick reference.

NOTE

If you have already read Chapter 12, "ColdFusion Scripting", much of this section may seem a bit redundant. However, ColdFusion's scripting language is quite a bit different from JavaScript. In some ways, the two languages can be said to be very similar, particularly with respect to the statements they support, and the way the basic syntax works (curly braces, parentheses, and so on). They are completely different in other ways, such as the operators they support and the way they treat objects.


JavaScript Language Elements

While it's not possible to fully introduce you to the JavaScript language in these pages, it's important for you to at least understand the basic language elements available to you. The next few pages list each of the core JavaScript statements, and can be used as a sort of mini-reference. If you need further information about these items, they will be covered in detail in any JavaScript book or comparable online resource.

For clarity, I have broken the statements into four groups:

  • Basic statements

  • Statements for looping

  • Statements for creating functions

  • Statements for error handling

The Basic Statements

Table 17.1 lists the basic JavaScript statements. By "basic", I just mean all the statements that aren't specifically for looping, creating functions, or error handling.

Table 17.1. Basic JavaScript Statements

STATEMENT

DESCRIPTION

if .. else

Implements simple if / else processing. Comparable to the <cfif> and <cfelse> tags in CFML.

switch

Executes different blocks of code based on the current value of some variable or expression. Comparable to the <cfswitch> and <cfcase> tags in CFML.

with

Establishes the default object for evaluating methods and properties. Generally used to make code easier to read and type. Though handy when used correctly, with is not for the faint of heart because it can lead to confusing unexpected behavior. There is no direct equivalent in CFML.

var

Creates a variable that is local to the current context. Generally, var is used to create variables that are only visible within the body of a function. Comparable to the <cfset var> syntax allowed within CFML <cffunction> blocks.


Statements for Looping

Like CFML, JavaScript provides a number of different ways to loop over blocks of code. Table 17.2 lists the various types of JavaScript loops, which correspond to various flavors of the <cfloop> tag in CFML.

Table 17.2. JavaScript Statements for Looping

STATEMENT

DESCRIPTION

for

The simplest and most familiar type of loop. Creates a loop block that advances the value of a counter with each iteration; the loop continues until the value reaches a certain value. Comparable to <cfloop> with from and to attributes in CFML.

for .. in

Creates a loop block that iterates over each of the values in a given object or array. Comparable to a <cfloop> with collection and item attributes in CFML.

while

Creates a loop block that executes until a particular condition is no longer true. If the condition is already false when the loop is encountered, it is skipped altogether. Similar to a <cfloop> that uses a condition attribute.

do .. while

Creates a loop block that executes until a particular condition is no longer true. The loop is guaranteed to execute at least once. There is no direct counterpart in CFML, but it's similar to a <cfloop> that uses a condition attribute.

break

Breaks out of a loop block. Execution continues on the first line following the loop block. Comparable to <cfbreak> in CFML.

continue

Skips the remainder of a loop block for the current pass through the loop. There is no direct counterpart in CFML.


Most for loops look like the following. This loop executes 10 times, advancing the value of i for each iteration:

 for (i = 0; i < 10; i++) {  ...your code here... } 

Here's a while loop that does the same thing:

 i = 0; while (i < 10) {  ...your code here...  i = i + 1; } 

Another while approach:

 i = 0; while (true) {  ...your code here...  i = i + 1;  if (i >= 10) {  break;  } } 

This for .. in loop is functionally equivalent:

 var myArray = [0,1,2,3,4,5,6,7,8,9]; for (i in myArray) {  ...your code here... } 

Statements for Creating Functions

Elsewhere in this book, you learn how to create your own functions for use in CFML code (see Chapter 12, "ColdFusion Scripting", for one method, and Chapter 19, "Creating ColdFusion Components", for another). You can also create functions for use in JavaScript code, using the statements listed in Table 17.3.

Table 17.3. JavaScript Statements for Creating Functions

STATEMENT

DESCRIPTION

function

Creates a function that can be called elsewhere by name; also establishes the function's input arguments, if any. Comparable to the <cffunction> and <cfargument> tags in CFML.

return

Stops function execution, returning a particular value as the function's output. Comparable to <cfreturn>, though return can be used anywhere within the body of a function, rather than only at the end.


Here's a function that returns the product of two numbers:

 function multiplyNumbers(num1, num2) {  return num1 * num2; } 

Here's another function that returns the absolute value (the positive version) of whatever number is passed to it (actually, there is a built-in Math.abs() function that does the same thing; I'm just trying to show as many statements working together as possible):

 function absoluteValue(number) {  var result;  if (number < 0) {  result = 0 - number;  } else {  result = number;  }  return result; } 

Statements for Error Handling

Table 17.4 lists the statements available for throwing and handling exceptions (errors) within your JavaScript code.

Table 17.4. JavaScript Error Handling Statements (recent browsers only)

STATEMENT

DESCRIPTION

try .. catch .. finally

Tries to execute a block of code, catching any exceptions. You can respond to the exceptions in the catch block, much like the <cfcatch> tag in CFML. Throws a custom exception (error). Comparable to <cfthrow> in CFML.

throw

Throws a custom exception (error). Comparable to <cfthrow> in CFML. This is a relatively recent addition to JavaScript and is not available in all browsers.


The following code snippet shows the basic form of the try..catch..finally construct. If you include this code in a web page, you will first see the "I will now try..." message, then the value of the firstName variable. If you comment out the var line at the top, you will see the "Hmm, looks like..." message, which proves that the catch block executes whenever a problem (such as a reference to a nonexistent variable) occurs. In either case, the message in the finally block will always be displayed, making the finally statement ideal for displaying status messages or taking final action regardless of whether problems occur.

 <script language="JavaScript" type="text/javascript">  try {  // Comment out the next line to see the error catching behavior  var firstName = "Winona";  alert("I will now try to display the value of the firstName variable.");  alert(firstName);  } catch(e) {  // If any errors occur...  alert("Hmmm, looks like there is no firstName variable. Sorry!");  } finally {  // This portion executes no matter what, error or no error  alert("Well, I hope you enjoyed our little exercise.");  } </SCRIPT> 

JavaScript Operators

Like any other language, JavaScript provides a set of operators for doing things like assigning values to variables or comparing values. Table 17.5 lists most of the JavaScript operators you are likely to encounter; refer to a JavaScript guide for a complete list. If you're familiar with C or Java, these operators will be very familiar to you. If not, that's okay, too.

Table 17.5. Abbreviated list of JavaScript Operators

STATEMENT

DESCRIPTION

=

Variable assignment, like in CFML.

==

Equality test, like EQ or IS in CFML.

!=

Inequality test, like NEQ or IS NOT in CFML.

++

Increments a value by one, as in i++ (which is a shortcut for i=i+1).

--

Decrements a value by one.

&&

Logical "and" operator, like AND in CFML. Just as in CFML, you can use parentheses to clarify what you want the operator to affect (same goes for the next two operators).

||

Logical "or" operator, like OR in CFML.

!

Logical "not" operator, like NOT in CFML.

+

Numeric addition or string concatenation. Be careful not to use & for string concatenation; that works in CFML but has a different meaning in JavaScript.

-

Numeric subtraction, as you would expect.

*

Numeric multiplication.

/

Numeric division.

%

Modulus (remainder after division), like MOD in CFML.


You'll see many of these operators sprinkled throughout the example listings and code snippets throughout this chapter.

Understanding the Core Objects

JavaScript also provides a number of built-in objects, often called the core objects. Many of these objects represent data types, like String or Date. Table 17.6 lists some of the most commonly used core objects, many of which you will see used throughout this chapter. Consult a JavaScript reference for a complete list of the methods and properties exposed by these objects.

Table 17.6. Core JavaScript Objects (Abridged)

OBJECT

DESCRIPTION

Array

Array objects expose helpful methods such as .reverse() and .sort(). The length of an array is available in the .length property.

Date

Date objects provide various date-manipulation methods such as .getMonth() and .toLocaleString().

Math

You don't create instances of this object; instead you use its methods directly, as in Math.round(), Math.abs(), and Math.random().

Object

Use the Object type to create your own custom objects that hold whatever data you need. Creating a new object is very similar conceptually to creating a new structure with StructNew() in CFML.

String

Any string object has a number of helpful methods, like .substring(), .toLowerCase(), .toUpperCase() , and .indexOf(), which is kind of like CFML's Find() function. The length of a string is available in the .length property.


Understanding JavaScript's Relationship to Web Browsers

JavaScript was originally designed by Netscape as a simple, lightweight scripting language that would work well in Web browsers. As such, people often get a little bit confused, thinking that JavaScript is something that is exclusively used in browsers.

Not so. JavaScript is a language that can be used in many different contexts, in browsers, on servers, and in many other types of applications. Here's a partial list of the places where JavaScript (the scripting language, not the <script> tag) can be used:

  • Web browsers. This remains the most obvious example, and the one that will be discussed directly in this chapter.

  • Email clients. These days, many email clients are just extensions of each vendor's respective Web browser technology, and provide much of the same support for JavaScript.

  • Macromedia Flash applications. Beginning with version 5, Flash movies are scripted using ActionScript, which is very similar to JavaScript.

  • Active Server Pages (ASP) pages. Many people think of ASP pages as something that you can only write with Visual Basic style syntax (VBScript), but ASP pages can also be written with JScript, which is essentially yet another form of JavaScript.

  • Windows Scripting Host (WSH) scripts. These scripts can be used to create macros that interact directly with the Windows shell.

  • Macromedia Dreamweaver, for creating tag editor dialogs and other custom extensions. HomeSite+ (formerly ColdFusion Studio) also exposes an extension API to JavaScript.

  • ColdFusion, to the extent that CFScript bears a striking relationship to JavaScript. It can't really be considered compatible with JavaScript, since it doesn't include support for the core objects listed in Table 17.5, but it's a pretty close cousin nonetheless. For details about CFScript, see Chapter 12, "ColdFusion Scripting".

NOTE

I'm skipping over some rather acrimonious contentious history when I say that JScript, ActionScript, and CFScript are essentially synonyms for JavaScript. JavaScript came first, developed by Netscape for version 2.0 of their browser. The language was later turned over to a standards body and evolved into the open specification known as EMCAScript, upon which JScript and ActionScript are officially based upon. Okay, even that is an oversimplification. Regardless of history, and regardless of the relevance of standards, the real-world intent of JScript and ActionScript are clearly to look, feel, and otherwise work like JavaScript.


So, while although JavaScript is most often used in Web browsers, that's not the only place where it can be used. That's an important point to understand, and which brings us to our next topic: understanding scripting object models.

Understanding Scripting Object Models

Because JavaScript is designed to be used in many different contexts (see the bulleted list in the previous section), the context-specific stuff is kept separate from the language itself. Everything relevant to the specific context (say, a Web page or a form if the context is a browser, or the position of the cursor if the context is Dreamweaver) is exposed to JavaScript in the form of a set of scriptable objects, or object model.

So, within any given context, there are really to things to know and understand:

  • The JavaScript language itself. Think of the language as consisting mainly of the items listed in Table 17.1 through Table 17.5, plus the various operators and semantic elements like curly braces and semicolons.

  • The object model specific to the context. Assuming that the context is a web Web browser, then the object model includes scriptable representations of browser and Web page concepts (like the URL for the current document, the size of the browser window, and information about the image and form fields on the page).

TIP

If it helps, think of JavaScript itself as the language used to talk to the browser, and the object model as what you talk about. The language, then, is just a way of speaking; the object model is the actual subject of your conversation.


The JavaScript language is really pretty simple. It's the object model supported by each browser that can get pretty complicated and potentially confusing. While each browser and version supports more or less the same language (JavaScript, which hasn't changed very much over the years), the object model exposed to JavaScript can differ quite a bit between browsers and versions. The differences between the object models exposed by Netscape and Microsoft browsers, for instance, were wildly different during the 4.x and 5.x versions of the respective products. Version 6.0 brought the object models much closer together in terms of scope, functionality, and overall design. Going forward, you can expect most scripts to work identically in IE, Firefox, Netscape, Mozilla, and Opera, especially if you stay away from whatever the latest-and-greatest feature of the moment happens to be.

JavaScript Objects Available in Web Pages

The scripting object model exposes a large number of objects that you can control via script within each Web page. Table 17.7 provides a list of some of the most important objects you can control with JavaScript, and some of their properties and methods.

Table 17.7. A Short List of Scriptable Objects in Web Pages

OBJECT

DESCRIPTION

document

The document object contains information about the current web Web page, including the location, forms, images, and frames properties listed in this table. You can refer to other elements on the page (<div>, <span>, <table>, and other areas) using the getElementById() method, assuming that you have given the element an ID attribute in your HTML code. From there you can, among other things, change the text displayed in an area using the element's innerHTML property (this is demonstrated briefly in Listing 17.12).

document.location

The document.location object allows you to inspect and control the URL of the current document. Reading the document.location.href property returns the current URL; setting the property causes the browser to navigate to another page (as if a link was clicked). The document.location. replace() method also navigates the browser to another page, but where the new page takes the place of the current page in the user's page history (, which means that the user can't use the Back button to return to the current page).

document.forms

This property is a collection (basically an array) of <form> blocks on the page. document.forms[0] refers to the first form, document.forms[1] refers to the second form (if any), and so on. If there are no forms on the page, document.forms.length will be zero. The various text input fields, drop-down lists, checkboxes, and so on in each form can be accessed as discussed in Table 17.10.

document.images

This property is a collection of objects that represent each <IMG> element in the current document. Documents can be referred to by index, such as document.images[0] for the first image on the page, or by the value of their name attribute, as in document.images.MyImage or document. images["MyImage"]. Among other things, you can cause a different image to appear by setting one of these object's' src propertyproperties; this is how image rollovers work. You can see an example of changing what image is displayed in the Film Browser example later in this chapter (Listing 17.7).

document.frames

This property is a collection of frames, if any, within the current document. The first frame is document.frames[0], and so on. <iframe> blocks are included as well. If there are no frames (that is, if the current document is not a <frameset> page and contains no <iframe> tags), then document.frames.length is zero.

window

The window object represents the current browser window (as opposed to the document, which sits within the window). You can open new windows (including pop-up windows) with window.open(), and can close the current window with window.close(). The window object also exposes a few utility methods, such as the setInterval() and clearInterval() methods for creating timers (demonstrated in Listing 17.12).


Understanding JavaScript Events

JavaScript supports scriptable events. Events generally occur when something changes, such as the loaded status of a document, or the value of a form field. You can provide JavaScript code that should be executed when an event occurs by including an attribute with the same name in your HTML. Such code is called an event handler.

Table 17.8 provides a short list of interesting events that are fired by various objects in the scripting object model. You'll see these events used throughout the examples in this chapter. This is by no means a complete list; it's just a sampling of the most commonly-used events, to give you an idea of what you can do. Consult a JavaScript reference for details.

Table 17.8. A Short List of Useful Events

ATTRIBUTE

DESCRIPTION

document.onload

Executes when the page first appears (is loaded) in the browser window. There is also an unload event that executes when the user leaves the page. To specify code to execute when the onload event fires, add an onload attribute to the document's <body> tag.

onclick

Many elements (especially form fields) support onclick events, which fire when the user clicks and then releases the mouse button over an object. The onclick event is used in the Film Browser example in Listing 17.7.

onchange

Most form field elements support onchange events, which execute when the user changes the value in a form field. In general, the event fires when the user is done making changes to a field (that is, when focus shifts away from the field), not for each keystroke. The event is used in Listing 17.1 as well as the various "cascading select list" examples throughout this chapter.

onkeyup and onkeydown

Most form field elements support these events, which fire when users use the keyboard to enter or change text. This event is also used in the Mortgage Calculator example in Listing 17.1.

onsubmit

This event fires when the user submits a form. Whatever JavaScript or function is called from this event can return a value of false to prevent the form from actually being submitted; this is the basis of most JavaScript form-validation routines. You can view source on a Web page that uses <cfform> validation to see how this works.


Including JavaScript Code in Web Pages

You can include JavaScript code in any Web page. Just place the code between a pair of <script> tags; you'll see examples of this throughout this chapter. Table 17.9 explains the attributes supported by the <script> tag.

Table 17.9. HTML <script> Tag Syntax

ATTRIBUTE

DESCRIPTION

language

The language that the script is written in. This value is usually JavaScript; that's the value used in this chapter's listings. You can also specify the JavaScript version, such as JavaScript1.1 or JavaScript1.2; such values cause subtle changes in behavior depending on the browser. In Microsoft browsers, you can also use JScript or VBScript. Consult a scripting reference for details. This attribute is technically deprecated in the current HTML specification, but remains the most common way of specifying a scripting language.

type

This is now the preferred way to specify the scripting language. For JavaScript, you use type="text/javascript". For maximum compatibility, provide both the language and type attributes. For modern browsers that support the HTML 4.01 standard, you can use type alone.

src

Optional. You can use the src attribute to include an external script file, which will be downloaded and executed by the browser. Conceptually, this is kind of like a <cfinclude> tag in CFML.

defer

You can add the optional defer flag if you would like to give the browser the option of not interpreting the script code until the page has finished loading. This can speed up the loading of your page, especially for users with slow connections, but can have side effects if you're not a bit careful. Consult a scripting reference for details.


Browser Specific Features and Compatibility Issues

JavaScript development can be a frustrating because of the varying degrees of compatibility between the various browsers in common use today. Again, in most causes the incompatibilities can be attributed to differences in the scriptable object models exposed to JavaScript rather than in the way the language itself works, but the end result is that JavaScript coders have had to work very hard to make certain kinds of scripts work with the major browsers. In particular, the portions of the scripting object model that pertain to Dynamic HTML (DHTML) have become notorious for not behaving the same way from browser to browser, version to version, and platform to platform.

NOTE

These days, many people use Macromedia Flash to perform the same kinds of things that they would otherwise do with DHTML. For this reason, I generally stay away from DHTML-related discussions in this chapter. As you will see, there are still plenty of other reasons to use JavaScript in your Web pages.


The situation got a lot better with the introduction of the Mozilla engine (usd by Netscape 6 and more recently Firefox). Mozilla and Internet Explorer share a comparatively enormous portion of their object models, all controllable via script.

For the sake of clarity and brevity, and because there would be too much to cover in this chapter otherwise, the examples in this chapter assume that you are using a new browser (IE6, Firefox, or Mozilla 6). Most of the examples will also work with earlier browsers (beginning, in general, with Netscape 3.0 and IE 4.0). Most JavaScript references and online guides will provide information on the various compatibilities and incompatibilities you need to keep in mind when working with older browsers.

That's the End of the Crash Course

The remainder of the chapter will explain how to perform some common tasks with JavaScript, focusing on situations where JavaScript and ColdFusion need to work together in some respect. You can use the tables that have appeared up to this point as a mini-reference guide for the various statements and objects used in the remaining sections. Wherever possible, the example listings will only use JavaScript syntax and elements that you have already learned, but in some cases you may need to refer to a full-fledged JavaScript reference to get all the details about a specific object, method, or property. A good place to find online references is http://msdn.microsoft.com.



Advanced Macromedia ColdFusion MX 7 Application Development
Advanced Macromedia ColdFusion MX 7 Application Development
ISBN: 0321292693
EAN: 2147483647
Year: 2006
Pages: 240
Authors: Ben Forta, et al

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