JavaScript Basics

Sang Shin, sang.shin@sun.com, www.javapassion.com/ajaxcodecamp


JavaScript is the glue that makes the whole Ajax operation possible.  And having good understanding on how JavaScript works is important for writing well-functioning Ajax applications.   In this hands-on lab, you will learn various capabilities of JavaScript language by writing and running JavaScript code.


Expected duration: 90-120 minutes

Prerequisites

This hands-on lab assumes you have some basic knowledge of, or programming experience with, the following technologies.

Software Needed


OS platforms you can use


Change Log


Lab Exercises



Exercise 1: Explore JavaScript events

In this exercise, you are going to see various examples of JavaScript code and then modify them and see the result.

  1. Learn when JavaScript code gets executed ("function.html")
  2. onblur event ("onBlurevent.html")
  3. onclick event ("onClickevent.html")
  4. onfocus event ("onFocusevent.html")
  5. onsubmit event ("onSubmitevent.html)
  6. Explore other events on your own

(1.1) Learn when JavaScript code gets executed ("function.html" )

The goal of this exercise is to understand when JavaScript code gets executed.  If the code is within a function, it gets executed only when the function gets invoked, typically as an event handler. If the code is outside of a function, it gets executed when a page that contains the code is loaded.

0. Start NetBeans IDE. 
1. Open samplejavascripts NetBeans project. 

2. Expand samplejavascripts->Web Pages.
3. Double-click function.html to open it in the source editor.   Please read the comments which are highlighted in the bold font. 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<script type="text/javascript">
   // The alert message below gets executed when the page is loaded
   alert("Hello Boston! This message gets displayed when a page is loaded.");
  
   // If alert("Hello world!!") below had not been written within a
   // function, it would have been executed when page is loaded.
   // Since it is within a function, it will be invoked only when
   // displaymessage() function is invoked.
   function displaymessage() {
        alert("Hello World! This message is within a function and gets displayed only when the function is called.")
   }
</script>
</head>

<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>
Code-1.10: function.html

4. Right-click function.html and select View. (Figure-1.11 below)  This will let the browser to load the function.html.


Figure-1.11: function.html

5. Observe that the browser gets displayed with the "Hello Boston! This message gets displayed when a page is loaded" alert message.  (Figure-1.12 below) (You might have to make the browser appear on the front screen if it behind other windows.) 
6. Click OK to close the alert message.


Figure-1.12: JavaScript code outside a function gets executed when a page is loaded

7. Click Click me! button. (Figure-1.13 below)  This will invoke displaymessage() function.


Figure-1.13: Clicking the button invokes an event handler

8. Observe that "Hello World! This message is within a function and gets displayed only when the function is called" alert message gets displayed. (Figure-1.14 below).
9. Click OK to close the alert message.


Figure-1.14: JavaScript code within a function gets executed

10. For your own exercise, please do the following tasks.  When you make a change, please make sure you save the change first by selecting File from the top-level menu and Save before selecting View.

                                                                                                                return to top of the exercise

(1.2) onblur event ("onBlurevent.html")

The goal of this exercise is to learn how onblur event occurs, which an event handler is invoked by the event. 

1. Double-click onBlurevent.html to open it in the source editor. (Figure-1.21 below)   Please read the comments which are highlighted in the bold font.

<html>
<head>
<script type="text/javascript">
    // Event handler of the first onBlur event   
    function upperCase() {
        var x=document.getElementById("fname").value;
        document.getElementById("fname").value= "Uppercase -" +
                                                x.toUpperCase();
    }
   
    // Event handler of the second onBlur event   
    function lowerCase() {
        var y=document.getElementById("lname").value;
        document.getElementById("lname").value= "Lowercase -" +
                                                y.toLowerCase();
    }
</script>
</head>

<body>

Enter your first name:
<!-- onblur event is generated when the input form field loses the focus -->
<input type="text" id="fname" onblur="upperCase()">

<br>

Enter your last name:
<!-- onblur event is generated when the input form field loses the focus -->
<input type="text" id="lname" onblur="lowerCase()">

</body>
</html>
Code-1.21: onBlurevent.html

2. Right-click onBlurevent.html and select View.
3. Observe that the browser gets displayed with two input form fields. 
4. Enter  your  first name, for example, Sang, into the first input form field.  (Figure-1.22 below)


Figure-1.22: Executing onBlurevent.html

5. Press Tab key or move your mouse outside of the input form field.  This will cause onblur event to be generated and the upperCase() function will be invoked as an event handler. You should see the first name you typed is converted into upper case letters. (Figure-1.23 below)


Figure-1.23: Effect of the onblur event

6. Enter  your  last name, for example, Shin, into the second input form field.
7. Press Tab key or move your mouse outside of the input form field.  This will cause onblur event to be generated and the lowerCase() function will be invoked as an event handler. You should see the last name you typed is converted into lower case letters. (Figure-1.24 below)


Figure-1.24: Effect of the onblur event

8. For your own exercise, please do the following tasks.  When you make a change, please make sure you save the change first by selecting File from the top-level menu and Save before selecting View.

                                                                                                                return to top of the exercise


(1.3)  onclick event (onClickevent.html)

The goal of this exercise is to learn how onclick event occurs and an event handler is  invoked as a result. 

1. Double-click onClickevent.html to open it in the source editor. (Figure-1.31 below)   Please read the comments which are highlighted in the bold font.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
    <head>
        <title>onClick event</title>
        <SCRIPT LANGUAGE="JavaScript">
            // Event handler of onclick event
            function testResults (form) {
                var TestVar = form.inputbox.value;
                alert ("You typed: " + TestVar);
            }
        </SCRIPT>
    </head>
    <body>
        <FORM NAME="myform" ACTION="" METHOD="GET">Enter something in the box: <BR>
            <INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
            <!-- When the button is clicked, onclick event is generated -->
            <INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)">
        </FORM>
    </body>
</html>
Code-1.31: onClickevent.html

2. Right-click onClickevent.html and select View.
3. Observe that the browser gets displayed with one input form field and a button. (Figure-1.32 below)


Figure-1.32: Display of the page

4. Type some characters, for example, Passion!, into the input form field.
5. Click Click button.  This will cause onclick event to be generated and the testResults() function will be invoked as an event handler.  (Figure-1.33 below)


Figure-1.33: Effect of the onclick event



                                                                                                                return to top of the exercise


(1.4)  onfocus event (onFocusevent.html)

The goal of this exercise is to learn how onfocus event occurs and an event handler is invoked as a result.  The onfocus event gets generated when an element gets a focus.

1. Double-click onFocusevent.html to open it in the source editor. (Figure-1.41 below)   Please read the comments which are highlighted in the bold font.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<script type="text/javascript">
    // Event handler of onfocus event   
    function upperCase() {
        document.getElementById("fname").value= "Enter your first name";
    }
   
    // Event handler of onfocus event   
    function lowerCase() {
        document.getElementById("lname").value= "Enter your last name";
    }
</script>
</head>

<body>

Enter your first name:
<!-- onfocus event is generated when the input form field gets a focus -->
<input type="text" id="fname" onfocus="upperCase()">

<br>

Enter your last name:
<!-- onfocus event is generated when the input form field gets a focus -->
<input type="text" id="lname" onfocus="lowerCase()">

</body>
</html>
Code-1.41: onFocusevent.html

2. Right-click onFocusevent.html and select View.
3. Observe that the browser gets displayed with two input form fields.
4. Move your mouse into the first text field and click your mouse.  You will see "Enter your first name" gets displayed.
5. Move your mouse into the second text field and click your mouse. You will see "Enter your last name" gets displayed.  (Figure-1.42 below)


Figure-1.42: Effect of onfocus event

6. For your own exercise, please do the following tasks.  When you make a change, please make sure you save the change first by selecting File from the top-level menu and Save before selecting View.


                                                                                                                return to top of the exercise


(1.5)  onsubmit event (onSubmitevent.html)

The goal of this exercise is to learn how onsubmit event occurs and an event handler is invoked as a result.  The event handler performs the input validation.

1. Double-click onSubmitevent.html to open it in the source editor. (Figure-1.51 below)   Please read the comments which are highlighted in the bold font. 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<script type="text/javascript">
    // This function gets called when onsubmit event occurs.
    // This function performs input form validation.
    function validate() {
       var at=document.getElementById("email").value.indexOf("@")
       var age=document.getElementById("age").value
       var fname=document.getElementById("fname").value
       submitOK="true"

       if (fname.length>10) {
           alert("The name must be less than 10 characters")
           submitOK="false"
       }
       if (isNaN(age)||age<1||age>100) {
           alert("The age must be a number between 1 and 100")
           submitOK="false"
       }
       if (at==-1) {
           alert("Not a valid e-mail!")
           submitOK="false"
       }
       if (submitOK=="false") {
           return false
       }
    }
</script>
</head>

<body>
    <!-- onsubmit event occurs when the submit button is clicked -->
    <form action="tryjs_submitpage.html" onsubmit="return validate()">
            Name (max 10 characters): <input type="text" id="fname" size="20"><br />
            Age (from 1 to 100): <input type="text" id="age" size="20"><br />
            E-mail: <input type="text" id="email" size="20"><br />
            <br />
        <input type="submit" value="Submit">
    </form>
</body>
Code-1.51: onSubmitevent.html

2. Right-click onSubmitevent.html and select View.
3. Observe that the browser gets displayed with three input form fields and a button.
4. Type 200 in the Age (from 1 to 100) input form field.
5. Observe "The age must be a number between 1 and 100" alert message gets displayed. (Figure-1.52 below)


Figure-1.52: Input form validation through onsubmit event

6. For your own exercise, please do the following tasks.  When you make a change, please make sure you save the change first by selecting File from the top-level menu and Save before selecting View.



                                                                                                                return to top of the exercise


(1.6)  Explore other events on your own

The goal of this step is to explore other events on your own.  Please see list of events from this link.  Try to write event handlers for the events you have not tried in this exercise.




Summary

In this exercise, you learned when JavaScript code gets executed.  You also learned how various events are generated and how corresponding event handlers are invoked.

                                                                                                                 return to the top



Exercise 2: Create JavaScript objects

In this exercise, you are going to create your own JavaScript objects using the using various schemes.


(2.1) Create a direct instance of a JavaScript object

The goal of this exercise is to learn how to create a direct instance of JavaScript object and how to add properties and methods to it.

1. Double-click createobjectdirectly.html to open it in the source editor. (Figure-2.11 below)   Please read the comments which are highlighted in the bold font.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<script type="text/javascript">
    // This is a function that is added as a method of a JavaScript object
    function myMethod(){
        alert("myMethod is invoked!");
    }
</script>
</head>
<body>
<h1> Example of creating a JavaScript object directly</h1>
<script type="text/javascript">

    // Create a direct instance of JavaScript object and add properties
    personObj=new Object();
    personObj.firstname="John";
    personObj.lastname="Doe";
    personObj.age=50;
    personObj.eyecolor="blue";

    // This is equivalent to println statement of Java programming language
    document.write(personObj.firstname + " is " + personObj.age + " years old.")

    // Add a method
    personObj.myMethod=myMethod;
   
    // Invoke a method
    personObj.myMethod(); 
   
</script>
</body>
</html>
Code-2.11: createobjectdirectly.html

2. Right-click createobjectdirectly.html and select View.
3. Observe that the browser gets displayed with properties of the JavaScript object is displayed and a method of it is also invoked. (Figure-2.12 below)


Figure-2.12: Creating a JavaScript object directly

4. Modify createobjectdirectly.html as shown in Code-2.13 below. The code fragments that need to be added are highlighted in bold and blue-colored font. This is to add your own direct instance of JavaScript object and add properties and methods to it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<script type="text/javascript">
    // This is a function that is added as a method of a JavaScript object
    function myMethod(){
        alert("myMethod is invoked!");
    }
    // This is a my own function that is added as a method of a JavaScript object
    function myOwnMethod(){
        alert("myOwnMethod is invoked!");
    }
</script>
</head>
<body>
<h1> Example of creating a JavaScript object directly</h1>
<script type="text/javascript">

    // Create a direct instance of JavaScript object and add properties
    personObj=new Object();
    personObj.firstname="John";
    personObj.lastname="Doe";
    personObj.age=50;
    personObj.eyecolor="blue";

    // This is equivalent to println statement of Java programming language
    document.write(personObj.firstname + " is " + personObj.age + " years old.")

    // Add a method
    personObj.myMethod=myMethod;
   
    // Invoke a method
    personObj.myMethod(); 

    // Create my own direct instance of JavaScript object and add properties
    addressObj=new Object();
    addressObj.street="5 Dreamland";
    addressObj.city="Seoul";
    addressObj.country="Korea";
    addressObj.zip=12345;

    document.write( "My own address is " + addressObj.street + " " + addressObj.city + " " +
                               addressObj.country + " " + addressObj.zip )

    // Add a method
    addressObj.myOwnMethod=myOwnMethod;
   
    // Invoke a method
    addressObj.myOwnMethod(); 
   
</script>
</body>
</html>
Code-2.13: Myown direct instance of JavaScript object is added

5. Right-click File from the top-level menu and select Save.  If you skip this, the changes you made will not be reflected in the subsequent step.
6. Right-click createobjectdirectly.html and select View.

7. For your own exercise, please do the following tasks.



                                                                                                                return to top of the exercise


(2.2) Create a JavaScript object through a template

The goal of this exercise is to learn how to create a JavaScript object through a template.

1. Double-click createobjectbytemplate.html to open it in the source editor. (Figure-2.21 below)   Please read the comments which are highlighted in the bold font.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<script type="text/javascript">
    // This is a function that is added as a method of a JavaScript object
    function myMethod(name){
        alert("myMethod is invoked! The name of the person is " + name);
    }   
</script>
</head>

<body>
<h1> Example of creating a JavaScript object through a template</h1>
<script type="text/javascript">

    // Define a template.  Note that a template is just a function.
    // The properties are needed to be initialized with this.
    function person(firstname,lastname,age,eyecolor){
        this.firstname=firstname
        this.lastname=lastname
        this.age=age
        this.eyecolor=eyecolor
    }

    // Create a person object
    myFather=new person("John","Doe",50,"blue")

    document.write(myFather.firstname + " is " + myFather.age + " years old.")

    // Add a method
    myFather.myMethod=myMethod;
   
    // Invoke a method
    myFather.myMethod(myFather.firstname); 
</script>

</body>
</html>    
Code-2.21: createobjectbytemplate.html

2. Right-click createobjectbytemplate.html and select View.
3. Observe that the browser gets displayed with properties of the JavaScript object is displayed and a method of it is also invoked. (Figure-2.22 below)


Figure-2.22: Creating a JavaScript object through a template

                                                                                                                return to top of the exercise


(2.3) Create another JavaScript object via template


Supposed you want to create the 2nd person object as shown in Code-2.31 below.  And you might expect you can invoke the newly added method from the 2nd object.  So let's do the experimentation.

1. Modify the createobjectbytemplate.html as shown in Code-2.23 below.  The code fragments that need to be added are highlighted in bold and blue colored font.  (This code is already provided as createobjectbytemplate2ndobjecterror.html if you do not want to type.)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<script type="text/javascript">
    // This is a function that is added as a method of a JavaScript object
    function myMethod(name){
        alert("myMethod is invoked! The name is " + name);
    }
</script>
</head>

<body>
<h1> Example of creating a JavaScript object through a template</h1>
<script type="text/javascript">

    // Define a template.  Note that a template is just a function.
    // The properties are needed to be initialized with this.
    function person(firstname,lastname,age,eyecolor){
        this.firstname=firstname;
        this.lastname=lastname;
        this.age=age;
        this.eyecolor=eyecolor;
    }

    // Create a person object
    myFather=new person("John","Doe",50,"blue");

    document.write(myFather.firstname + " is " + myFather.age + " years old.");

    // Add a method
    myFather.myMethod=myMethod;
   
    // Invoke a method
    myFather.myMethod(myFather.firstname);
 
    // Create another person object
    myMother=new person("Sallie", "Lowe", 56, "brown");
   
    // Invoke the same method.  This will not work.
    myMother.myMethod(myMother.firstname);
</script>

</body>
</html>
Code-2.31: Modified createobjectbytemplate.html

2. Click File from the top-level menu and select Save.
3. Right-click createobjectbytemplate.html and select View.
4. Observe that the browser gets displayed with properties of the first JavaScript object is displayed and a method of it is also invoked. (Figure-2.22 above) Click OK.
5. Observe a method from the second JavaScript object (myMother) is not displayed. 
6. Enable FireBug debugger by pressing F12 key. 
7. Observe that myMother.myMethod is not a function error condition has occurred. (Figure-2.32 below) 


Figure-2.32: Error condition detected

So question you might want to ask is "how can I modify the template so that all objects can access the newly added method or properties?".  Well, the answer is "You will have to redefine the template".  So let's do just that.

8. Modify the createobjectbytemplate.html as shown in Code-2.33 below.  The code fragments that need to be added are highlighted in bold and blue colored font.  (This code is already provided as createobjectbytemplate2ndobject.html if you do not want to type.)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<script type="text/javascript">
    // This is a function that is added as a method of a JavaScript object
    function myMethod(name){
        alert("myMethod is invoked! The name is " + name);
    }
</script>
</head>

<body>
<h1> Example of creating a JavaScript object through a template</h1>
<script type="text/javascript">

    // Define a template.  Note that a template is just a function.
    // The properties are needed to be initialized with this.
    function person(firstname,lastname,age,eyecolor){
        this.firstname=firstname;
        this.lastname=lastname;
        this.age=age;
        this.eyecolor=eyecolor;
    }

    // Create a person object
    myFather=new person("John","Doe",50,"blue");

    document.write(myFather.firstname + " is " + myFather.age + " years old.");

    // Redefine the template
     function person(firstname,lastname,age,eyecolor){
        this.firstname=firstname;
        this.lastname=lastname;
        this.age=age;
        this.eyecolor=eyecolor;
       
        //Add a method
        this.myMethod=myMethod;
    }
   
    // Invoke a method
    myFather.myMethod(myFather.firstname);
 
    // Create another person object
    myMother=new person("Sallie", "Lowe", 56, "brown");
   
    // Invoke the same method.  This should not work.
    myMother.myMethod(myMother.firstname);
</script>

</body>
</html>
Code-2.33: Modified createobjectbytemplate.html

9. Select File from top-level menu and select Save All.
10. Right-click createobjectbytemplate.html and select View.
11. Observe that the browser gets displayed with properties of the first JavaScript object is displayed and a method of it is also invoked. (Figure-2.22 above) Click OK.
12. Observe that the browser gets displayed with properties of the first JavaScript object is displayed and a method of it is also invoked. (Figure-2.34 below) Click OK.


Figure-2.34: Effect of modifying the template

                                                                                                                return to top of the exercise


Summary

In this exercise, you have learned how to create your own JavaScript objects and how to access the properties and methods of them.


                                                                                                                          return to the top


Exercise 3: Create a separate JavaScript file


In this exercise, you are going to create a separate JavaScript file (instead of including all JavaScript code inside either HTML or JSP page).  We are going to use the example code we have used in the Exercise 2 above.
  1. Create myOwnJavaScript.js file in the top directory
  2. Create myOwn2ndJavaScript.js file in the subdirectory

(3.1) Create myOwnJavaScript.js file in the top directory

In this step, you are going to create myOwnJavaScript.js file in the top directory.

1. Right click samplejavascripts->Web Pages and select New->File Folder.
2. If you have installed NetBeans JavaScript editor plug-in, you can select the JavaScript under Categories and JSTemplate.js from the File Type. (Figure-3.11 below)


Figure-3.11: Create new JavaScript file

Trouble-shooting: If you don't see the JavaScript under Categories, it is because you have not installed JavaScript plug-in which was mentioned above.

3. Observe that New JSTemplate.js dialog box appears.
4. For the File Name: field, type in myOwnJavaScript. (Figuire-3.12 below) Click Finish button.  Since you are going to create it under the top directory, take the default value of Folder field.


Figure-3.12: New JSTemplate.js dialog box

5. Observe that myOwnJavaScript.js file node appears on the left under Web Pages and a blank contents of the myOwnJavaScript.js is displayed in the source editor on the right.
6. Replace the blank contents of the myOwnJavaScript.js with the code shown in Code-3.13 below.  Note that you do not have to wrap the JavaScript code with the <script ..>..</script> tag.

    // This is a function that is added as a method of a JavaScript object
    function myMethod(name){
        alert("myMethod is invoked! The name is " + name);
    }
Code-3.13: Modified myOwnJavaScript.js

7. Modify the createobjectbytemplate.html as shown in Code-2.33 below.  The code fragments that need to be removed are highlighted in bold and red-colored font. The code fragments that need to be added are highlighted in bold and blue colored font

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<!-- ------------- Code fragment that is removed ------------------------
<script type="text/javascript">
    // This is a function that is added as a method of a JavaScript object
    function myMethod(name){
        alert("myMethod is invoked! The name is " + name);
    }
</script>
----------------------------------------------------------------------------->
<script language="JavaScript"
            type="text/javascript"
            src="myOwnJavaScript.js">               

</script> 
</head>

<body>
<h1> Example of creating a JavaScript object through a template</h1>
<script type="text/javascript">

    // Define a template.  Note that a template is just a function.
    // The properties are needed to be initialized with this.
    function person(firstname,lastname,age,eyecolor){
        this.firstname=firstname;
        this.lastname=lastname;
        this.age=age;
        this.eyecolor=eyecolor;
    }

    // Create a person object
    myFather=new person("John","Doe",50,"blue");

    document.write(myFather.firstname + " is " + myFather.age + " years old.");

    // Redefine the template
     function person(firstname,lastname,age,eyecolor){
        this.firstname=firstname;
        this.lastname=lastname;
        this.age=age;
        this.eyecolor=eyecolor;
       
        //Add a method
        this.myMethod=myMethod;
    }
   
    // Invoke a method
    myFather.myMethod(myFather.firstname);
 
    // Create another person object
    myMother=new person("Sallie", "Lowe", 56, "brown");
   
    // Invoke the same method.  This should not work.
    myMother.myMethod(myMother.firstname);
</script>

</body>
</html>
Code-2.33: Modified createobjectbytemplate.html

8. Select File from top-level menu and select Save All.
9. Right-click createobjectbytemplate.html and select View.
10. Observe that the browser gets displayed with properties of the first JavaScript object is displayed and a method of it is also invoked. (Figure-2.22 above) Click OK.
11. Observe that the browser gets displayed with properties of the first JavaScript object is displayed and a method of it is also invoked. (Figure-2.34 above) Click OK.

                                                                                                                return to top of the exercise

(3.2) Create myOwn2ndJavaScript.js file in a sub-directory

In this step, you are going to create myOwn2ndJavaScript.js file in a subdirectory. 

1. Right click samplejavascripts->Web Pages and select New->File Folder.
2. If you have installed NetBeans JavaScript editor plug-in, you can select the JavaScript under Categories and JSTemplate.js from the File Type.
3. Observe that New JSTemplate.js dialog box appears.
4. For the File Name: field, type in myOwnJavaScript.
5. For the Folder: field, type web\myOwnSubdirectory. (Figure-3.21 below) Click Finish button. 


Figure-3.21: Create a new JavaScript file in a subdirectory

6. Observe that myOwn2ndJavaScript.js file node appears under myOwnSubDirectory on the left under Web Pages and a blank contents of the myOwn2ndJavaScript.js is displayed in the source editor on the right.
7. Replace the blank contents of the myOwn2ndJavaScript.js with the code shown in Code-3.22 below.  Note that you do not have to wrap the JavaScript code with the <script ..>..</script> tag.

    // This is a function that is added as a method of a JavaScript object
    function my2ndMethod(age){
        alert("my2ndMethod is invoked! The age is " + age);
    }
Code-3.22: Modified myOwn2ndJavaScript.js

7. Modify the createobjectbytemplate.html as shown in Code-3.23 below.   The code fragments that need to be added are highlighted in bold and blue colored font

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<script language="JavaScript"
            type="text/javascript"
            src="myOwnJavaScript.js">              
</script> 
<script language="JavaScript"
            type="text/javascript"
            src="myOwnSubdirectory/myOwn2ndJavaScript.js">
</script>
</head>

<body>
<h1> Example of creating a JavaScript object through a template</h1>
<script type="text/javascript">

    // Define a template.  Note that a template is just a function.
    // The properties are needed to be initialized with this.
    function person(firstname,lastname,age,eyecolor){
        this.firstname=firstname;
        this.lastname=lastname;
        this.age=age;
        this.eyecolor=eyecolor;
    }

    // Create a person object
    myFather=new person("John","Doe",50,"blue");

    document.write(myFather.firstname + " is " + myFather.age + " years old.");

    // Redefine the template
     function person(firstname,lastname,age,eyecolor){
        this.firstname=firstname;
        this.lastname=lastname;
        this.age=age;
        this.eyecolor=eyecolor;
       
        //Add a method
        this.myMethod=myMethod;

        //Add a 2nd method
        this.my2ndMethod=my2ndMethod;
    }
   
    // Invoke a method
    myFather.myMethod(myFather.firstname);
 
    // Create another person object
    myMother=new person("Sallie", "Lowe", 56, "brown");
   
    // Invoke the same method.  This should work.
    myMother.myMethod(myMother.firstname);
   
    // Invoke the 2nd method
    myMother.my2ndMethod(myMother.age);
</script>

</body>
</html>
Code-3.23: Modified createobjectbytemplate.html

8. Select File from top-level menu and select Save All.
9. Right-click createobjectbytemplate.html and select View.
10. Observe that the browser gets displayed with properties of the first JavaScript object is displayed and a method of it is also invoked. (Figure-2.22 above) Click OK.
11. Observe that the browser gets displayed with properties of the first JavaScript object is displayed and a method of it is also invoked. (Figure-2.34 above) Click OK.
12. Observe that my2ndMethod is invoked. (Figure-3.24 below)


Figure-3.24: Invoking a method that is defined in the 2nd JavaScript file

                                                                                                                return to top of the exercise

Summary

In this exercise, you have learned how to create JavaScript file as a separate and how to access them from your JavaScript code.


                                                                                                                return to the top


Exercise 4: Detecting the presence of JVM


The goal of this exercise is to learn how to detect the presence of JVM and the version number in the browser through JavaScript. 

(4.1) Detecting the presence of JVM


1. Double-click detectjvm.html under simplejavascropts->Web Pages to open it in the source editor. (Figure-4.11 below)   Please study the code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<body>

<script type="text/javascript">
if(window.navigator.javaEnabled()){
    alert("JVM is present in your browser! Version is " + java.lang.System.getProperty("java.version"));}
else{
    alert("JVM is NOT present in your browser!");
}
</script>

</body>
</html>
Code-4.11: detectjvm.html

2. Right-click detectjvm.html and select View.
3. Observe that the browser gets displayed with an alert message, which shows if JVM is present or not and the version number. (Figure-4.22 below)


Figure-4.22: JVM is present or not

Trouble-shooting:  The above code is working with Firefox and Netscape browser but does not seem to be working with IE.  If you know the solution, please let me(sang.shin@sun.com) know.   (According to Joh Boles - The problem is that IE does not support LiveConnect like almost all other browsers.  The only way that I know of to get the JavaScript code to work is to embed an applet and then use it to communicate the JVM version and other Java properties.  This is how we do it for our application when the IE browser is used.)



Homework exercise (for people who are taking Sang Shin's "AJAX online course") - 4 hours


The goal of this homework exercise is to let you exercise the things you learned so far from the presentation and hands-on lab at the same time to let you explore other features of JavaScript that have not been covered in the presentation and hands-on lab but using the excellent learning material from w3schools.com.

1. Write myOwnJavascript.html as following.  (You can just add a new HTML file to the samplejavascripts project if you are using NetBeans.)
2. Write myOwnJavaScript.js as a separate file
3. Do the JavaScript Quiz Test from w3schools.com.  (No need to submit anything on this)

4. Send the following files to ajaxhomework@sun.com with Subject as AJAXHomework-ajaxjavascript.

                                                                                                                                                return to the top