Previous Page TOC Next Page



- 19 -
Introduction to JavaScript


As you begin to integrate your Visual J++ applets into your HTML documents you will probably find that it would be useful if you could dynamically communicate between your applet and the other HTML components on the page. For example, you might want to have the user enter information into an HTML form and then have this information passed to your applet for processing.

This type of communication can be accomplished through scripting. There are currently two popular scripting languages available: JavaScript and VBScript. Today, you will learn the basics of JavaScript. VBScript will be introduced tomorrow and then on the last day, you will learn how to use both scripting languages to communicate between a script, an applet, and an ActiveX component.

What is JavaScript?


Although JavaScript is similar to Java, it is not the same. Originally called LiveScript, JavaScript was designed by Netscape to be a scripting language that can be embedded into HTML files. It is not compiled, but instead is interpreted by the browser. Unlike Java, which is first converted to easy-to-compile byte codes, JavaScript is read by the browser as source code. This makes it easy for you to learn JavaScript by example because you can see how others are using JavaScript in their pages.

This chapter will present the JavaScript programming language so that you can successfully implement JavaScript into your HTML files.

A Simple Example


We will first start with a simple example that shows you the JavaScript language and gives you an idea of some of the things that are possible. The following program will prompt the user for his or her name and then display a short message using the name that was entered. You can enter this program using a simple text editor and then view the file with a JavaScript capable Web browser, such as Internet Explorer or Netscape Navigator.




<HTML><HEAD>



<TITLE>A JavaScript Example</TITLE>



<SCRIPT LANGUAGE="JavaScript">



var name = window.prompt("Hello! What is your name?","");



document.write("Hello " + name + "! I hope you like JavaScript!");



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

Figure 19.1 shows the input prompt while Figure 19.2 shows the output to the screen after entering your name.

Figure 19.1. A JavaScript example before entering a name.

Figure 19.2. A JavaScript example after entering a name.

This example displays a prompt with the window.prompt method. The value obtained is stored in a variable called name. The variable is then combined with other strings and displayed in the browser's window using the document.write method.

Now that you have seen a brief glimpse of the functionality available through JavaScript, you will continue with a tutorial of the language itself.

The SCRIPT Tag


The <SCRIPT>. . .</SCRIPT> pair of tags is what tells the browser that a script is enclosed in an HTML document. The <SCRIPT> tags can appear either in the <HEAD> or <BODY> section of the HTML file. The advantage of placing it in the <HEAD> section is that it will be loaded and ready before the rest of the document loads.

The only attribute currently defined for the <SCRIPT> tag is LANGUAGE=. This attribute is used to specify the scripting language. There are currently two values defined: JavaScript and VBScript. For your JavaScript programs you should use the following syntax:




<SCRIPT LANGUAGE="JavaScript">



// INSERT ALL JavaScript HERE



</SCRIPT>


You might have noticed that the comment is not enclosed in normal <- and -> tags for HTML comments. This is because JavaScript supports the same style comments as C and Java. Both the single line // syntax and the/*. . .*/ syntax for multiple lines is supported.

The difference in the syntax for comments between HTML and JavaScript allows you to hide the JavaScript code inside an HTML comment. This will hide the JavaScript from older browsers that don't support it, such as the following example:




<SCRIPT LANGUAGE="JavaScript">



<!-- From here the JavaScript code is hidden



// INSERT ALL JavaScript HERE



// this is where the hiding ends -->



</SCRIPT>

The // is necessary on the last line of the script so that the browser will not try to interpret the line as JavaScript code. The examples in this chapter will not include the JavaScript hiding feature; this simply helps make the code a little more readable.

Data Types


Unlike C++ or Java, JavaScript is a loosely typed language. This means that you do not have to specify a data type when a variable is declared. The data types are automatically converted to the appropriate type as necessary.

Consider the following example:




<HTML><HEAD>



<TITLE>A Data Type Example</TITLE>



<SCRIPT LANGUAGE="JavaScript">



var fruit = 'apples';



var numfruit = 12;



numfruit = numfruit + 20;



var temp = "There are " + numfruit + " " + fruit + ".";



document.write(temp);



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

JavaScript-enabled browsers will correctly handle the preceding example with the following output:




There are 32 apples.

The JavaScript interpreter will treat the numfruit variable as an integer when 20 is added and then as a string when it is combined into the temp variable.

Variables


As you have seen in the examples so far, JavaScript supports the use of variables.



A JavaScript variable must start with a letter or an underscore. A number cannot be used as the first character of a variable name, but can be used after the first character. JavaScript is case-sensitive.

There are two different scopes available for variables: global and local. A global variable can be accessed anywhere in the application (HTML file). A local variable can only be accessed in the current function. Global variables are simply declared as follows:




x = 0;

A local variable is declared inside a function with the var keyword, for example:




var x = 0;

A global variable may use the var statement as well, but it is not necessary.

Literals


Literals are values in a program that don't change; they are constant. In JavaScript there isn't a CONST type, such as in Visual Basic and C, that can be used to represent some constant value. In JavaScript, this is done by simply using a variable. JavaScript literals can be broken into four categories: integers, floating points, Booleans, and strings. Each of these will be discussed in the following sections.

Integers


Integers in JavaScript are represented as follows:


Floating Point


A floating point literal is comprised of the following parts:

In order to be classified as a floating point literal, as opposed to an integer, there must be at least one digit followed by either a decimal point or e (or E). Examples of floating point literals are


Boolean


The Boolean literal is used to indicate a true or false condition. There are two values:


String


A string literal is represented by zero or more characters enclosed in either single or double quotes (they must match at both ends!). The following are examples of string literals:

In C, C++, and Java the single quote is used to indicate a single character. This is NOT the case in JavaScript, where the single quote and double quote can be used interchangeably to represent a string of characters.

JavaScript supports several special characters that can be inside a string. These are as follows:


Expressions


A set of literals, variables, and/or operators that evaluate to a single value is an expression. The single value can be either a string, a number, or a Boolean value. There are essentially three types of expressions in JavaScript:


Arithmetic Expressions


Arithmetic expressions evaluate to a number. For example:

( 3 + 4 ) * (84.5 / 3) would evaluate to 197.1666666667

String Expressions


String expressions evaluate to a string. For example:




"The dog barked " + barktone + "!"

might evaluate to The dog barked ferociously!.

Logical Expressions


Logical expressions evaluate to a Boolean. For example:




temp > 32

might evaluate to false.

JavaScript supports a conditional expression as well. The syntax for this is




(condition) ? valTrue : valFalse

If condition evaluates to true, the expression evaluates to valTrue; if false, the expression evaluates to valFalse. Consider the following example:




state = (temp > 32) ? "liquid" : "solid"

In this example, the variable state would be assigned the value of liquid if the variable temp was greater than 32. Otherwise, the value of state would be set to solid.

Operators


Like most programming languages, JavaScript provides an array of operators for your use. The operators available in JavaScript can be grouped into the following major categories:


Assignment Operators


The assignment operator is the equal sign, =, which assigns the value of the right operand to the left operand. In addition, JavaScript supports several shortcut operators as follows:

There are also some shortcut bitwise operators:

x |= y means x = x | y


Comparison Operators


The purpose of a comparison operator is to compare two operands and return true or false based on the comparison. The following comparison operators are supported by JavaScript:


Arithmetic Operators


In addition to the standard operators (+, -, *, /) for addition, subtraction, multiplication, and division, JavaScript support the following additional arithmetic operators:



If you are assigning the result of an increment or decrement to another variable, such as y = x++, there are different results, depending upon whether the ++ or -- appears before or after the variable name (x in this case). If the ++ or -– is used before x (prescript) then x would be incremented or decremented before the value of x is assigned to y. If the ++ or -- is after x (postscript), the value of x is assigned to y before it is incremented or decremented.


String Operator


When used with a string, the + operator becomes the concatenation operator and will simply combine the two strings. For example,




"abc" + "xyz"

will evaluate to abcxyz.

Logical Operators


JavaScript supports the following logical operators:


Bitwise Operators


For bitwise operations, the values are first converted to 32-bit integers and then evaluated bit by bit. The following operators are supported:

There are also several bitwise shift operators available. These are also converted to 32-bits for the shift operation. They are converted to the type of the left operand when complete. The bitwise shift operators are as follows:


Statements


The statements that are available in JavaScript can be grouped into the following categories:


Conditional Statements


Conditional statements provide the ability for a program to make a decision and perform specific actions based on the result of that decision. JavaScript provides this support through the if. . .else statement.

if. . .else

The if. . .else statement allows you to check for a certain condition and execute statements based on that condition. The optional else statement allows you to specify a set of statements to execute if the condition is not true.




if (condition) {



   statements for true condition }



else {



   statements for false condition}

The following is an example:




if (x == 10) {



   document.write("x is equal to 10, setting x=0.");



   x = 0; }



else



   document.write("x is not equal to 10.");


The { and } characters are used to separate blocks of code, just like in C, C++, or Java. For example, notice that the { and } were used for the true condition in the preceding example because there were two lines of statements. The false condition is only a one line statement so the { and } are not necessary.


Loop Statements


Loop statements provide a means for looping through a section of code until an expression evaluates to true. JavaScript provides two types of loop statements:


for. . .

The for loop will set an initial expression, initExpr, then loop through a section of JavaScript statements as long as a condition expression evaluates to true. Each time through the loop the expression incrExpr is executed.




for (initExpr; condition; incrExpr) {



// statements to execute while looping



}

The following is an example:




for (x=1; x<=10; x++){



y = x * 25;



document.write("x="+ x + " y=" + y + "<BR>");



}

The preceding example will loop through the code until x is greater than 10. The output can be seen in Figure 19.3.

Figure 19.3. A for loop example.

while. . .

The while loop will continue as long as a specified condition evaluates to true.




while (condition) {



//  statement to execute while looping;



}

The following is an example:




x = 1;



while (x <= 10) {



y = x * 25;



document.write("x="+ x + " y=" + y + "<BR>");



x++;



}

The preceding example will produce the same result as the for loop example in Figure 19.3.

break

The break statement can be used to terminate the execution of a for or while loop. The program flow will continue at the statement following the end of the loop.




break;

The following is an example:

The following example will loop until x is greater than or equal to 100. However, if the loop is entered with a value less than 50 then the loop will terminate and execution will continue after the loop.




while (x < 100) {



   if (x < 50) break;



   x++;



}

continue

The continue statement is similar to the break statement except that execution is terminated and restarted at the beginning of the loop. For a while loop, control is returned to the condition. For a for loop, control is returned to the incrExpr.




continue;

The following is an example:

The following example will increment x from 0 to 5, skip to 8, and continue incrementing to 10.




x = 0;



while (x <= 10) {



   document.write("The value of x is " + x + "<BR>");



   if (x == 5) {



      x = 8;



      continue;



   }



   x++;



}

Object Manipulation Statements


JavaScript includes several statements that are designed to work with objects.

for. . .in

The for. . .in statement is used to loop through all the properties of an object. The variable can be any arbitrary variable name that you desire. It is simply needed to give you something to refer to as you use the property in statements inside the loop. The following example should help in understanding this statement.



Microsoft Internet Explorer 3.0 does not properly support the for. . .in statement. The following example will only work in Netscape Navigator 3.0.




for (variable in object) {



//  statements



   }

The following example will cycle through all of the properties of the Window object and print the name of each property. The output is shown in Figure 19.4.




<HTML><HEAD>



<TITLE>A For In Example</TITLE>



<SCRIPT LANGUAGE="JavaScript">



document.write("The properties of the Window object are: <BR>");



for (var x in window){



   document.write(x + "<BR>");



}



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

Figure 19.4. Output from the for. . .in example.

new

The new variable is used to create a new instance of an object.




objectvar = new objecttype ( param1 [, param2] … [,paramN] )

The following example will create an object called person that will have the properties of firstname, lastname, age, and sex. Note that the this keyword is used to refer to the object in the person function. Then, two instances of person will be created using the new statement.




<HTML><HEAD>



<TITLE>A New Example</TITLE>



<SCRIPT LANGUAGE="JavaScript">



function person(firstname, lastname, age, sex){



   this.firstname = firstname;



   this.lastname = lastname;



   this.age = age;



   this.sex = sex;



}



person1= new person("Logan", "Blankenbeckler", "1", "Male");



person2= new person("Kimberly", "Blankenbeckler", "27", "Female");



document.write("The first person's name is ", person1.firstname + ". <BR>");



document.write("The second person's name is ", person2.firstname + ".");



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

this

The this keyword is used to refer to the current object. The calling object is generally the current object in a method or function.




this[.property]

See the previous example for new for a demonstration of this.

with

The with statement is used to set the default object for a series of statements. The properties can then be referred to without using the parent object.




with(object){



   statements;



}

The following example shows the use of the with statement to set the default object to document so that the write method can be used without having to refer to the document object itself, such as document.write.




<HTML><HEAD>



<TITLE>A With Example</TITLE>



<SCRIPT LANGUAGE="JavaScript">



with (document) {



   write("This is an example of the things that can be done <BR>");



   write("with the <B>with</B> statement.<P>");



   write("This can really save some typing!");



}



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

Functions


JavaScript supports the use of functions. Although not necessary, a function may have one or more parameters and one return value. Because JavaScript is a loosely typed language, it is not necessary to define parameter or return types for a JavaScript function. In addition, a function may be a property of an object, in which case it will act as a method for that object.




function fnName([param1][,param2]…[,paramN]){



   // function statements;



}

The following example shows how to create and use a function as a member of an object. The printStats function is created as a method of the object person.




<HTML><HEAD>



<TITLE>A Function Example</TITLE>



<SCRIPT LANGUAGE="JavaScript">



function person(firstname, lastname, age, sex){



   this.firstname = firstname;



   this.lastname = lastname;



   this.age = age;



   this.sex = sex;



   this.printStats = printStats;   //makes printStats a method of person



}



function printStats(){



   document.write(this.firstname + " " + this.lastname + "'s stats are:<BR>");



   document.write("Age: " + this.age + "<BR>");



   document.write("Sex: " + this.sex + "<BR>");



}



person1= new person("David", "Blankenbeckler", "27", "Male");



person2= new person("Kimberly", "Blankenbeckler", "27", "Female");



person1.printStats();



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

Built-in Functions


JavaScript contains several built-in functions. These functions are built into the language itself and are not a part of an object. The built-in functions are


eval

The eval function is used to evaluate expressions or statements. Any expression, statement, or object property can be evaluated. This is useful for evaluating expressions that are entered by the user (otherwise it could be evaluated directly).




returnval = eval( any legal Java expressions or statements )

The following is an example:




<HTML><HEAD>



<TITLE>An Eval Example</TITLE>



<SCRIPT LANGUAGE="JavaScript">



var string = "10 + Math.sqrt(64)";



document.write(string + " = " + eval(string));



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

parseInt

The parseInt function takes a string value and attempts to convert it to a integer of the specified base. The base is specified by an optional second parameter. This function can be used to convert different bases back to base 10 or to ensure that character entered data is converted to integer before being used in calculations. In the case of bad input data, the parseInt function will read and convert a string until the point where it finds non-numeric characters. In addition, parseInt will truncate floating point numbers.




parseInt(string [, radix]);

The following is an example:




<HTML><HEAD>



<TITLE>An parseInt Example</TITLE>



<SCRIPT LANGUAGE="JavaScript">



document.write("Converting 0xC hex to base-10: " + parseInt(0xC, 10) + "<BR>");



document.write("Converting 1100 binary to base-10: " + parseInt(1100, 2));



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

parseFloat

This built-in function is similar to the parseInt function except that it returns a floating-point representation of string input.




parseFloat(string);

The following example shows how parseFloat works for several different types of strings. The output is shown in Figure 19.5.




<HTML><HEAD>



<TITLE>An parseFloat Example</TITLE>



<SCRIPT LANGUAGE="JavaScript">



document.write("This script will show how different strings ");



document.write("are converted using parseFloat.<BR>");



document.write(parseFloat("137") + "<BR>");



document.write(parseFloat("137abc") + "<BR>");



document.write(parseFloat("abc137") + "<BR>");



document.write(parseFloat("1abc37") + "<BR>");



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

Figure 19.5. Screen output from parseFloat example.

Arrays


Although there is no explicit support for arrays, Netscape published a method that allows you to create your own. This is accomplished by creating a function that initializes the array as follows:




function InitArray(numElements) {



   this.length = numElements;



   for (var x = 1; x <= numElements; x++) {



       this[x] = 0 }



   return this;



}

This will create an array of the specified size and fill it with zero. Note that the first element is the length of the array and should not be used.

To create an array, you simply do the following:




myArray = new InitArray(10);

This will create myArray[1] through myArray[10], with each element containing a zero. The array can be populated with data as follows:




myArray[1] = "South Carolina";



myArray[2] = "Oregon";

The following is a full example:




<HTML><HEAD>



<TITLE>An Array Example</TITLE>



<SCRIPT LANGUAGE="JavaScript">



function InitArray(numElements) {



   this.length = numElements;



   for (var x = 1; x <= numElements; x++) {



       this[x] = 0 }



   return this;



}



myArray = new InitArray(10);



myArray[1] = "South Carolina";



myArray[2] = "Oregon";



document.write(myArray[1] + "<BR>");



document.write(myArray[2] + "<BR>");



</SCRIPT>



</HEAD>



<BODY>



</BODY>



</HTML>

The output should appear as follows:




South Carolina



Oregon

Events


JavaScript is an event-driven language. An event-driven program can respond to certain events, such as a mouse click or the loading of a document. An event can cause a section of code to execute (known as an event handler) to allow the program to respond appropriately.

Event Handlers


The program that responds to an event is called an event handler. The event handler is specified as an attribute of an HTML tag:




<tagName eventHandler="JavaScript Code or Function">

The following example will call the CheckAge() function when the value of the text field is changed.




<INPUT TYPE=TEXT NAME="AGE" onChange="CheckAge()">

The eventHandler code does not have to be a function. It can be JavaScript statements separated by semi-colons. However, for purposes of modularity and code cleanliness, it is typically a separate function.

The following list describes the event handlers available in JavaScript:

The following example shows a simple event handler script that will validate a value entered into a text field. The user's age is entered in the field and the event handler will check to be sure that a valid age was entered. If not, a message will appear asking the user to re-enter the value. The event handler is called when the AGE field is changed and the focus is moved to another field. The screen output is shown in Figure 19.6.




<HTML>



<HEAD>



<TITLE>An Event Handler Example</TITLE>



<SCRIPT LANGUAGE="JavaScript">



function CheckAge(form) {



   if ((form.age.value < 0) || (form.age.value > 120)) {



      alert("Please enter your real age!");



      form.age.value = 0;



   }



}



</SCRIPT>



</HEAD>



<BODY>



<FORM NAME="SURVEY">



Please enter your name and age:<BR>



First<INPUT TYPE=TEXT NAME="FNAME" MAXLENGTH=15 SIZE=10>



MI<INPUT TYPE=TEXT NAME="MI" MAXLENGTH=1 SIZE=1>



Last<INPUT TYPE=TEXT NAME="LNAME" MAXLENGTH=20 SIZE=15><BR><BR>



Age<INPUT TYPE=TEXT NAME="AGE" MAXLENGTH=3 SIZE=2 onChange="CheckAge(SURVEY)">



<P>



Please select your favorite season of the year:<BR>



Spring<INPUT TYPE=RADIO NAME="SEASON" VALUE="Spring">



Summer<INPUT TYPE=RADIO NAME="SEASON" VALUE="Summer">



Fall  <INPUT TYPE=RADIO NAME="SEASON" VALUE="Fall">



Winter<INPUT TYPE=RADIO NAME="SEASON" VALUE="Winter">



<P>



Please check all of the outdoor activities that you enjoy:<BR>



Hiking<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Hiking">



Skiing<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Sking">



Water Sports<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Water">



Cycling<INPUT TYPE=CHECKBOX NAME="ACT" VALUE="Cycling">



<P>



<INPUT TYPE=SUBMIT><INPUT TYPE=RESET>



</FORM>



</BODY>



</HTML>

Figure 19.6. An event handler example.

JavaScript Objects


JavaScript is an object-based language. It is not an object-oriented programming language primarily because it does not support classes or inheritance. This section will present the objects available for your JavaScript programs.

In the JavaScript object hierarchy, the descendant objects are actually properties of the parent object. Referring to the previous example for the event handler, the form, named SURVEY, would be a property of the document object; the text field, named AGE, would be a property of the form. To reference the value of AGE, you could use the following:




document.SURVEY.AGE.value

Objects in JavaScript have properties, methods, and event handlers associated with them. For example, the Document object has a title property. This property reflects the contents of the <TITLE> tag for the document. In addition, you have seen the Document.write method used in many of the examples. This method is used to output text to the document.

Objects can also have event handlers. For example, the Link object has two event handlers: onClick and onMouseOver. The onClick event handler is invoked when a link object is clicked with the mouse, while the onMouseOver is invoked when the mouse pointer passes over the link.

You will not cover all of the details of JavaScript objects today. However, each of the properties, methods, and event handlers for each JavaScript object are presented in Appendix E for your reference.

Summary


This chapter provided a brief introduction to the JavaScript language. In addition, this chapter will serve as a useful reference during the development of your JavaScript applications.

Although this chapter, combined with Appendix E, provides a complete, concise reference to the JavaScript language, the subject is broad enough that entire books have been written about it. One useful book is Teach Yourself JavaScript 1.1 in a Week by Arman Danesh from Sams.net Publishing.

Because JavaScript is still a new and changing language, the reader should also refer to Netscape's Web site for the latest information concerning the language. Netscape is located at the following address:

http://www.netscape.com/

Tomorrow, you will learn about another choice for scripting, VBScript. On Day 21, you will learn how to use both scripting languages to control both applets and ActiveX components.

Q&A


Q: Why would I want to use a script when I can build all of the functionality I need into an applet?

A: Script provides the capability for you to easily customize your Web applications based on more generically designed applets and ActiveX controls. For example, you might design an applet to render a graphical image based on user input that is received through HTML form controls and ActiveX controls. Through the use of a scripting language, such as JavaScript or VBScript, you can communicate between these various components. Scripting is also very powerful when used simply for form validation, as in the example shown in Figure 19.6.

Q: I already know Visual Basic and would rather just use VBScript. What are the advantages of using JavaScript?

A: JavaScript has one major advantage over VBScript in that it is supported by a large majority of Web browsers, which primarily consists of Netscape Navigator 3.0 and Microsoft Internet Explorer 3.0. VBScript, on the other hand, is currently only supported by Microsoft's browser and does not appear to be in Netscape's plans for future versions.

Q: I did not notice any mention of error handling in JavaScript. What error handling capabilities does JavaScript have?

A: JavaScript does not have any built-in error handling capabilities like Visual C++ or Java. One method of preventing errors for numeric calculations might be the parseInt and parseFloat built-in functions. These functions can be used to ensure that user-entered data is valid before attempting a calculation.

Previous Page Page Top TOC Next Page