Chapter V.3. JavaScript

The problem with most Web pages is that they're static, much like staring at a page from a book except displayed on a computer screen. Although nothing's wrong with static Web pages for displaying information, you may want to create interactive Web pages that can respond to the user's actions. To create interactive or dynamic Web pages, computer scientists developed various programming languages dubbed scripting languages. Although you can choose several languages for creating dynamic Web pages, the most popular scripting language is JavaScript.

JavaScript programs are stored either as part of a Web page file or in a separate file altogether. When you visit a Web site, the computer storing the Web pages (the server) sends its Web pages and JavaScript files to your computer (the client). Your computer now runs an interpreter to run the JavaScript programs.

Instead of creating standalone applications like a systems programming language can do (such as C++ or BASIC), JavaScript programs are often much shorter and designed to create simpler programs. For example, a JavaScript program may display a text box for you to type a password. Whatever you type, the JavaScript program can verify if the password is valid and then decide whether to let you into the Web site.

Because JavaScript works with most browsers and computers, JavaScript is a simple and easy way to create dynamic Web pages without relying on browser plug-ins that users might not have or want. However, one major disadvantage is that JavaScript programs may run slowly. Even worse, some people turn off JavaScript support to speed up their browser. So if your Web pages rely on JavaScript, anyone who turned off JavaScript won't see your fancy Web pages.

Despite its name, JavaScript is a completely different programming language from Java, although both languages borrow heavily from the C++ syntax that includes the use of curly brackets and semicolons ending each statement.

Note

On the Mac OS X, Dashboard widgets, which are tiny programs that pop up on the screen, are made with JavaScript code.

The Structure of a JavaScript Program

At the simplest level, a JavaScript program can consist of one or more commands, such as

<html>
  <script language=javascript>
    document.writeln("This is a simple JavaScript program.");
  </script>
  <body>
  </body>
</html>

The <script> and </script> tags define the beginning and ending of a JavaScript program. The first <script> tag identifies the scripting language used, which in this case is always JavaScript. Sandwiched in between the two <script> tags are the actual JavaScript commands.

However, it's more common to divide a JavaScript program into functions with each function acting like a separate building block. For example, a simple JavaScript program might look like this:

<html>
  <script language=javascript>
    <!--
    function hello() {
      window.alert("This is also a simple JavaScript
   program.");
    }
    -->
  </script>
  <body onLoad = "hello()">
  </body>
</html>

The onLoad command tells your computer when to run a particular function.

As an alternative to storing JavaScript code directly in the HTML code of a Web page, you can store JavaScript programs in separate files. Then you need to define the name of that JavaScript file to load and run it within your Web page, such as

<html>
  <script language=javascript src="filename.js"></script>
  <body>
  </body>
</html>

Creating Comments

To write a comment in JavaScript, use the double slash character so that anything that appears to the right is a comment, such as

<html>
  // The JavaScript code is stored in a file that
  // has the .js file extension.
  <script language=javascript src="filename.js"></script>
  <body>
  </body>
</html>

The double slash character is handy for adding a comment to a single line. If you want to write a comment over multiple lines, you can use the /* and */ characters, such as

<html>
  /* The JavaScript code is stored in a file that
    has the .js file extension. */
  <script language=javascript src="filename.js"></script>
  <body>
  </body>
</html>

Declaring Variables

JavaScript variables can hold any type of data, such as numeric (integers and decimals), strings ("like this"), Boolean values (True or False), or nothing at all (defined as null). JavaScript variables act like temporary containers that can hold any data. One moment it might hold an integer, the next a decimal value, and then a string.

To declare a variable in JavaScript, you must use the var keyword followed by the variable name, such as

var VariableName;

VariableName can be any descriptive name. Because JavaScript is a case-sensitive language, it treats My2008Tax as a completely different variable than my2008tax. Some programmers use uppercase letters to make variable names easier to find whereas others use all lowercase. To declare multiple variables, just cram them all on a single line, separated by a comma, such as

var VariableName1, VariableName2, VariableName3;

Using Operators

The three types of operators used are mathematical, relational, and logical. Mathematical operators calculate numeric results such as adding, multiplying, or dividing numbers, as shown in Table 3-1.

Table V.3-1. Mathematical Operators

Mathematical Operator

Purpose

Example

+

Addition

5 + 3.4

-

Subtraction

203.9 - 9.12

*

Multiplication

39 * 146.7

/

Division

45 / 8.41

%

Modula division (returns the remainder)

35 % 9 = 8

The + operator can also concatenate two strings together, such as "Hi there," + "good looking." This would create one string that contains "Hi there, good looking."

Relational operators compare two values and return a True or False value. The six comparison operators available are shown in Table 3-2.

Table V.3-2. Relational Operators

Relational Operator

Purpose

==

Equal

!=

Not equal

<

Less than

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

Warning

The relational operator in JavaScript is two equal sign symbols (== ), whereas the relational operator in other programming languages is just a single equal sign symbol (= ). If you use only a single equal sign to compare two values in JavaScript, your program will work but not the way it's supposed to.

Logical operators compare two Boolean values (True or False) and return a single True or False value, as shown in Table 3-3.

Table V.3-3. Logical Operators

Logical Operator

Truth Table

&&

True && True = True

True && False = False

False && True = False

False && False = False

||

True || True = True

True || False = True

False || True = True

False || False = False

!

!True = False

!False = True

Increment and decrement operators

Like C/C++, JavaScript has special increment (++) and decrement (--) operators, which simply add or subtract 1 to a variable. Typically, adding 1 to a variable looks like this:

j = 5;
i = j + 1;

The increment operator replaces the + 1 portion with ++, such as

j = 5;
i = ++j;

In this example, the value of i is j + 1 or 6, and the value of j is also 6.

Warning

If you place the increment operator after the variable, such as

j = 5;
i = j++;

Now the value of i is 5, but the value of j is 6.

The decrement operator works the same way except that it subtracts 1 from a variable, such as

j = 5;
i = --j;

In this example, the value of i is j - 1 or 4, and the value of j is also 4.

Warning

If you place the decrement operator after the variable, such as

j = 5;
i = j--;

Now the value of i is 5, but the value of j is 4.

Assignment operators

Most programming languages use the equal sign to assign values to variables, such as

i = 59;

However, JavaScript also includes combination assignment and mathematical operators, as shown in Table 3-4.

Table V.3-4. Assignment Operators

Assignment Operator

Purpose

Example

+=

Addition assignment

i += 7 (equivalent to i = i + 7)

-=

Subtraction assignment

i -= 4 (equivalent to i = i - 4)

*=

Multiplication assignment

i *= y (equivalent to i = i * y)

/=

Division assignment

i /= 3.5 (equivalent to i = i / 3.5)

%=

Modulo assignment

i %= 2.8 (equivalent to i = i % 2.8)

Branching Statements

The simplest branching statement is an IF statement that only runs one or more commands if a Boolean condition is True, such as

if (condition) {
  Command;
  }

To make the computer choose between two mutually exclusive sets of commands, you can use an IF-ELSE statement, such as

if (condition) {
  Command; }
else {
  Command;
  }

As an alternative to the IF-ELSE statement, you can also use the SWITCH statement to offer two or more choices, such as

switch (expression) {
case value1:
  Command;
  break;
case value2:
  Command;
  break;
default:
  Command;
}

Warning

The SWITCH statement always needs to include the break command to tell the computer when to exit out of the SWITCH statement.

The above SWITCH statement is equivalent to the following IF-ELSE statement:

if (expression = value1) {
  Command;
  }
else if (expression = value2) {
  Command;
  }
else {
  Command;
  }

To check if a variable matches multiple values, you can stack multiple case statements, such as

switch (expression) {
case value1:
case value2:
  Command;
  break;
case value3:
case value4;
  Command;
  break;
default:
  Command;
}

This SWITCH statement is equivalent to the following IF-ELSE statement:

if (expression = value1) || (expression = value2) {
  Command;
  }
else if (expression = value3) || (expression = value4) {
  Command;
  }
else {
  Command;
  }

Looping Statements

A looping statement repeats one or more commands for a fixed number of times or until a certain Boolean condition becomes True. To create a loop that repeats for a fixed number of times, use the FOR loop, which looks like this:

for (startvalue; endvalue; increment) {
  Command;
  }

If you wanted the FOR loop to run four times, you could set the Start value to 1 and the End value to 4, such as

for (i = 1; i <= 4; i++) {
  Command;
  }

If you don't know how many times you need to repeat commands, use a WHILE loop, which looks like this:

while (condition) {
  Command;
}

If the condition is True, the loop runs at least once. If this condition is False, the loop doesn't run.

A variation of the WHILE loop is the DO-WHILE loop, which looks like this:

do {
  Command;
} while (condition);

The main difference between the two loops is that the WHILE loop may run zero or more times, but the DO-WHILE loop will always run at least once.

Warning

Somewhere inside a WHILE and DO-WHILE loop, you must have a command that can change the condition from True to False; otherwise, the loop will never end, and your program will appear to hang or freeze.

Creating Functions

In JavaScript, every subprogram is a function that can return a value. (A function that returns a null value simply acts like a procedure in other programming languages.) The format of a typical function looks like this:

function functionname (Parameter list)
  {
  Commands;
  return value;
  }

The two parts of a JavaScript function are

  • Parameter list: Defines any data and their data types that the function needs to work. If the function doesn't need to accept any values, the parameter list can be empty.

  • Return: Defines a value to return.

If a function doesn't return a value or accept any parameters, it might look like this:

function myfunction ()
  {
  Command;
  }

Using Arrays

JavaScript offers two ways to create an array. First, you can define an array and the elements inside that array by using square brackets like this:

var myarray = [data1, data2, data3];

JavaScript arrays can store any type of data, such as integers, decimal values, strings, or Boolean values like this:

var myarray = [93.42, "Hi there", 3];

Another way to create a JavaScript array is to define the array size and then store data in that array like this:

var myarray = new Array(x);

Here x is the size of the array, such as 4 or 9. After defining an array, you can store items in that array like this:

myarray[2] = "This works";

Note

JavaScript arrays are zero-based, which means if you define an array like this:

var myarray = new Array(2);

Warning

The array elements are numbered myarray[0], myarray[1], and myarray[2].

Designing User Interfaces

JavaScript can retrieve data from the user by creating different types of user interface elements, such as dialog boxes and windows. Such user interface items can display information to the user, creating an interactive Web page.

Creating dialog boxes

The three types of dialog boxes JavaScript can create are alert, confirmation, and prompt. An alert dialog box displays a message on the screen and gives the user the option of closing the dialog box. A confirmation dialog box displays a message and offers the user two or more choices. A prompt dialog box gives users a chance to type in data.

To create an alert dialog box, you need to define the text you want displayed, such as

alert("Message here");

An alert dialog box displays an OK button. As soon as the user clicks this OK button, the alert dialog box goes away.

A confirmation dialog box gives users a choice of OK and Cancel buttons. To create a confirmation dialog box, you must display text and include commands that do something when the user clicks either OK or Cancel:

if (confirm("Text message"))
  command;
else
  command;

The following JavaScript code creates a confirmation dialog box:

<html>
  <script language=javascript>
      <!--
    if (confirm("Do you want to retaliate with nuclear
   weapons?"))
       document.write("Now starting World War III.");
     else
       document.write ("Let's give peace a chance.");
   -->
  </script>
  <body>
  </body>
</html>

To create a prompt dialog box, you need to display text to appear in the dialog box and then optional text to appear as a default value, such as

prompt("Text to display", optionalvalue);

If you wanted to display the text "How many times do you think you'll be disappointed by your Presidential elections?" and display a default value of "Infinity", you'd use this JavaScript code:

<html>
  <script language=javascript>
      <!--
    prompt ("How many times do you think you'll be
   disappointed by your Presidential elections?",
   "Infinity");
      -->
  </script>
  <body>
  </body>
</html>

Creating windows

JavaScript can open windows, which can display additional Web pages inside. (Many browsers may include a feature to block pop-up windows. This feature blocks JavaScript from opening a window because many pop-up ads rely on JavaScript to display annoying ads on your screen.)

To create a window, you need to use the following:

variablename = window.open ("address");

So if you wanted to open the Dummies Web site, you could use this code:

mywindow = window.open ("http://www.dummies.com");
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset