Computer Science Illuminated, Third Edition

eLearning

Animated Flashcards
Live Wire
Cryptic Crossword Puzzles
Ethical Issues
Biographical Sketches
Did You Know
Goin Live
Google Code Digital Lab Manual
Online Glossary
The Learning Store
Language Library
Download PEP/7
Instructor Resources
Student Resources

eLearning Home

Lab #12

Introduction to JavaScript


12.1 What is JavaScript?

JavaScript is another tool that can help provide additional features to your web pages.  However, before we get into the details, we need to clear up a few things.  First off, JavaScript is not Java.  Java is a programming language created in 1995 by Sun Microsystems.  Java is used to create both computer applications and small programs (known as applets) which can be placed in a browser.  While applets are still found on the web, Java is more widely used in the creation of applications (programs).

JavaScript however, has little to do with Java, other than that they both evolved around the same time.  JavaScript is a scripting language which is used to provide program-like functionality in web pages.  JavaScript can be executed before web pages leave the server (server-side), or once the page is loaded into a browser (client-side).  We will concentrate on the latter.

Another point to mention when talking about JavaScript is compatibility with browsers.  Originally introduced by Netscape for use in their Navigator browser, Microsoft followed suit with a similar feature to their browsers.  Over time, both companies had their own similar, but different versions of client-side scripting.  Therefore, in this lab, we will try to introduce only concepts and examples that will work for both browsers.  In addition, the issue of compatibility means that when you are creating web pages which involve the use of JavaScript, you need to check the pages against more than one web browser.  Experienced developers will check their pages with both Microsoft's Internet Explorer and Netscape's Navigator browsers.  Another popular browser is the Mozilla browser, which is the underlying browser engine for Netscape's new browsers.  As Mozilla's popularity grows, so too will the need to check web pages against Mozilla as well.  (Mozilla was used in creating the screen captures and HTML editing of this series of labs.)

Back to JavaScript...  Client-side JavaScript is a series of interpreted procedural or object-oriented statements weaved into a web page.  (See your textbook for more information about procedural and object-oriented programming languages).  When included in a web page and the page is then loaded in a user's browser, JavaScript can:
  • affect the look of the page,
  • affect the look and feel of the browser,
  • provide additional content on the page, and
  • respond to user events such as mouse clicks.

12.2 Getting Started with JavaScript

To insert JavaScript into our web pages, we must place the script tag (<script>) in our web page at the desired location for the script (more on this later!).  To start with a simple example, we can add a JavaScript alert window to our web page by inserting the script tag and the code for the alert in the header of the document, as in the following code:

javascript.html
<html>
    <head><title>
Welcome to JavaScript!</title>
    <script
language="JavaScript">
       
alert("Welcome to JavaScript!");
    </script>
    </head>

   
    <body bgcolor="white">
    <center><h3>
Welcome to JavaScript!</h3></center>
    </body>
</html>


When the web page in the example above is loaded by the user's web browser, an alert is displayed for the user.  The contents of the alert are specified in the alert function call made in the JavaScript statement.  The resulting (initial) display is shown in Figure 1, below.

Our first JavaScripted web page
Figure 1: Our first JavaScripted web page

Taking things a bit further, we can declare a variable in our JavaScript and place a user-entered value in it for use later in the web page.  In the example below, we display a prompting window with the question "What is your name?".  The prompt window will remain displayed until the user clicks the OK button.  (Presumably the user has first answered the question in the text area, but there is no guarantee of this happening!)

Next, as the document is being rendered in the browser, we print the value of the user's entry as part of the H3 tag.  This second step is accomplished by using the document.write method call.  In JavaScript the document is a JavaScript object (as in object-oriented programming) which contains a method (function) named write.  By calling the write method and passing it a string (text enclosed in double quotes) we can modify the actual HTML document by providing custom HTML on-the-fly (as it happens)!  Figures 2 and 3 show the results of the prompting window and the resulting HTML document once it finally completely loads.

javascript2.html
<html>
    <head><title>
Welcome to JavaScript!</title>
    <script
language="JavaScript">
       
var result;
        result=prompt("What is your name?");
    </script>
    </head>

   
    <body bgcolor="white">
    <center>
    <script
language="JavaScript">
       
document.write("<h3>Hello, " + result + "!</h3>");
    </script>
    </center>
    </body>
</html>


Prompting the user for input
Figure 2: Prompting the user for input.

The resulting web page.
Figure 3: The resulting web page.

Lab Activity #1:
Add JavaScript to two of your web pages.  Add an alert to your main web page to welcome your users, similar to what was demonstrated above.

Then, on a different web page, add JavaScript to perform the following:
  1. declare three variables
  2. prompt the user to enter
  • an adjective,
  • a noun, and
  • a verb
In the body of the web page, use the document.write method call to create the following Mad Lib:
The <adjective> <noun> <verb> the novice web page developer.
Not sure what a Mad Lib is?  Check out the following:

12.3 Other things we can do

JavaScript has a number of built-in objects and functions which we can use within our scripts.  One example of this is the Date object which can be used to create and manipulate calendar dates.  Once these date objects are created, we can manipulate them or extract information from them.

For example, in the code below, we have added the creation of a new Date object (dateNow) to web page.  Then, in the body of the page, we can extract and print our date information.  (To keep the example simple, we have purposely placed nothing else on the web page, and limited the formatting to a bare minimum!)

javascript3.html
<html>
    <head><title>
Welcome to JavaScript!</title>
    <script
language="JavaScript">
       
var dateNow = new Date();
    </script>
    </head>

   
    <body bgcolor="white">
    <center>
    <script
language="JavaScript">
       
document.write("The current date is: <b>" + dateNow.getMonth() + "/");
        document.write(dateNow.getDay() + "/" + dateNow.getYear() + "</b><br>");
        document.write("The current time is: <b>" + dateNow.getHours() + ":");
        document.write(dateNow.getMinutes() + ":" + dateNow.getSeconds() + "</b>");
    </script>
    </center>
    </body>
</html>


If you use this code on your web page, you are likely to notice two things:
  • The year is a number offset from 1900.  That is, for a date in 2002, the year is represented as 102.  Thus, we need to add 1900 to the returned value from calling the getYear() method on the dateNow object.
  • If the minutes or seconds value is less than 10, there is no leading zero for the value.  So, for a time of 12:08:04, the value that would be printed would be 12:8:4.
Fortunately, both of these issues are easy to correct!  For the year problem, we will just stick in a '1900+' at the point we print the year value.  To keep it from acting like a printed string concatenated to another string, we will also enclose the addition expression in parentheses.

For the second problem, we will need to check the value and prepend a "0", if needed (if the value is <10).  To accomplish this, we will need to utilize two simple 'if' statements as well as introduce two additional temporary variables.

Both of these solutions are reflected in the code below and are followed by a screen capture of the resulting page.

javascript4.html
<html>
    <head><title>
Welcome to JavaScript!</title>
    <script language="JavaScript">
        var dateNow = new Date();
    </script>
    </head>
   
    <body bgcolor="white">
    <center>
    <script
language="JavaScript">
        document.write("The current date is: <b>" + dateNow.getMonth() + "/");
        document.write(dateNow.getDay() + "/" + (1900+dateNow.getYear()) + "</b><br>");
        document.write("The current time is: <b>" + dateNow.getHours() + ":");
        var minutes = dateNow.getMinutes();
        if (minutes < 10)
            minutes = "0" + minutes;
        var seconds = dateNow.getSeconds();
        if (seconds < 10)
            seconds = "0" + seconds;
       
        document.write(minutes + ":" + seconds + "</b>");
    </script>
    </center>
    </body>
</html>


Utilizing simple logic statements, expressions, and objects!
Figure 4: Utilizing simple logic statements, expressions, and objects!

Next, we will make the page a tad more complex.  If we would like to update the time, we currently have to reload the page.  However, by inserting a form and a function that recalculates and displays the time, we can have the function update the clock's time.

To accomplish this, we will add the form, our text in the form, and a text field to display the clock's time.  We will also add the updateForm function to recalculate and update the results.  Finally, we will add a timer to make it all happen.  The source code is listed below.

javascript5.html
<html>
    <head><title>
Welcome to JavaScript!</title>
    <script language="JavaScript">

        function updateForm() {
            var dateUpdate = new Date();
            var hrs = dateUpdate.getHours();
            var min = dateUpdate.getMinutes();
            var sec = dateUpdate.getSeconds();
           
            var minvalue;
            if (min < 10)
                minvalue = ":0" + min;
            else
                minvalue = ":"+ min;
           
            var secvalue;
            if (sec < 10)
                secvalue = ":0" + sec;
            else
                secvalue = ":" + sec;
               
            document.timeForm.timeField.value = dateUpdate.getHours() + minvalue + secvalue;
            setTimeout("updateForm()", 1000);
        }
    </script>
    </head>
   
    <body bgcolor="white">
    <center>
    <script language="JavaScript">

        var dateNow = new Date();
       
        document.write("The current date is: <b>" + (dateNow.getMonth()+1) + "/");
        document.write(dateNow.getDate() + "/" + dateNow.getFullYear() + "</b><br>");
        document.write("<form name=\"timeForm\">");
        document.write("The current time is: <input type=\"text\" size=\"10\" name=\"timeField\" value=\"");
        document.write(dateNow.getHours() + ":");
        document.write(dateNow.getMinutes() + ":" + dateNow.getSeconds() + "\"></input><br>");
        document.write("</form>");
        setTimeout("updateForm()", 1000);
    </script>
    </center>
    </body>
</html>


The JavaScript code in the body of the web page is really processed first.  When this happens, the initial display of the date and time takes place.  Notice that we neglected to correctly format the minutes and seconds to save a little space and to keep the example easy to read.

Pay particular attention to the form (named timeForm), text field (named timeField).  They become important in the updateForm function.  Once the page loads and the form is displayed, we set a timer (the setTimeout call) to call our function updateForm after 1000 milliseconds (1 second).

Then, after 1 second, the updateForm function is called.  Within the body of the function, a new Date object is created, the appropriate values obtained and then formatted using a few extra temporary variables (minvalue and secvalue).  Next, the form updates the value of the timeField in the timeForm, which updates what is displayed to the user (thereby updating the clock).  Before the function is done, we reset the timer (call setTimeout again) so that the form is updated in another second.

One last thing to point out with this example is that we only change the hours, minutes, and seconds in the updateForm function.  If you watch the form for a long enough time you will notice that the day, month, or year do not change!  This is not a bug, it was done by design (to keep the example simple, and to lead you to Lab Activity #2)!

  Our revised clock in a form.
Figure 5: Our revised clock in a form.

Lab Activity #2:
Enter the code from the javascript5.html file into one of your existing web pages.  Then, apply the following changes:
  1. Modify the updateForm function so that the hour is padded with a leading zero if the hour value is less than 10.
  2. Change the web page to include a text field (in the same form) for the date indicators (month/day/year).  Then, modify the updateForm function to also update the month, day, and year when appropriate.

12.4 Checking web forms

Speaking of forms on the web... JavaScript is quite often used to validate user input on web forms before the data is sent to the server.  In this fashion, we can reduce the processing load on the server by ensuring that the data has already been examined for errors or problems.  Consider the following simple example:

Let's say we have a form that asks the user to enter his or her name and email address.  Before storing this information on our server (so that we can send them spam email later, for example), we wish to ensure that:
  • the name field is not blank, and
  • the email address is valid (in the sense that it at least contains an at-symbol (@)
These checks are rather primitive, since any user could enter just a single letter for their name, and an at-symbol for their email address, but that's ok.  We want to keep the code simple at this point so that you get the picture.  (You will have a chance to expand on the checking functionality in Lab Activity #3!)

So first, we need our form.  The code listing from javascript6.html will provide that for us.  Figure 6 contains an image of this form in a browser.
javascript6.html
<html>
    <head><title>
Welcome to JavaScript!</title>
    </head>
   
    <body bgcolor="white">

    <center><h3>
Welcome to JavaScript!</h3></center>
    <form name="dataForm" action="http://someserver.com">
    <center>
        <label>Your Name:</label>&nbsp;&nbsp;
        <input type="text" size="40" name="username"></input><br><br>
        <label>Your Email:</label>&nbsp;&nbsp;
        <input type="text" size="40" name="email"></input><br><br>
        <input type="submit" name="submit" value="Submit results"></input>
    </form>

    </body>
</html>


The first view of our web form.
Figure 6: The first view of our web form.

Now that we have our form.  We'll want to create a function that checks the values of both fields in the forms when the user hits the "Submit results" button.  Essentially this function will display an alert window if it finds an error.

The function listed in javascript7.html (below) is the function which will perform our form validation for us.  For each piece of data (the user's name and email address), we first copy the value to a temporary variable.  Next, we set a flag (valid) to true.  This flag will indicate if the form is free of errors (and initially we will assume it is).

Next, we check the length of the namevalue temporary variable.  This variable currently holds the contents of the form's textfield named 'username'.  If the length of the value is <1 character long, then we know it was not filled in and left blank.  If this is the case, we present the user with an alert message and set our valid flag to false.

We next examine the emailvalue variable's length (to see if it is blank) and if it contains an at-symbol.  To check for the symbol, we will use the indexOf method and pass it the at-symbol character.  If the symbol is not present in the variable emailvalue, then the method will return a -1 value to us.  So, if either the length is less than 1 character, or if the value does not contain the at-symbol, we present an alert to the user and set the flag.

javascript7.html
<script language="JavaScript">
    function checkForm() {
        var namevalue = document.dataForm.username.value;
        var emailvalue = document.dataForm.email.value;
        var valid = true;

        if (namevalue.length < 1) {
            alert("The specified name is not valid!");
            valid = false;
        }
       
        if ((emailvalue.length < 1) || (emailvalue.indexOf('@') == -1)) {
            alert("The specified email address is not valid!");
            valid = false;
        }
       
        return valid;       
    }
    </script>

Finally, as the function finishes, we return the value of the valid variable.  How we tie it all together is the subject of the next bit of code...

We will add the onSubmit attribute to the form tag in our web page.  The onSubmit attribute will call the specified function (checkForm) and obtain the result returned by the function.  If the value is 'false', the form will not be submitted.  If the value is anything else, the form will then be submitted to the server for processing.

Thus, our final result looks like the following:

javascript8.html
<html>
    <head><title>
Welcome to JavaScript!</title>
    <script language="JavaScript">

    function checkForm() {
        var namevalue = document.dataForm.username.value;
        var emailvalue = document.dataForm.email.value;
        var valid = true;

        if (namevalue.length < 1) {
            alert("The specified name is not valid!");
            valid = false;
        }
       
        if ((emailvalue.length < 1) || (emailvalue.indexOf('@') == -1)) {
            alert("The specified email address is not valid!");
            valid = false;
        }
       
        return valid;       
    }
    </script>
    </head>
   
    <body bgcolor="white">

    <center><h3>
Welcome to JavaScript!</h3></center>
    <form name="dataForm" onSubmit="return checkForm()" action="http://someserver.com">
    <center>
        <label>
Your Name:</label>&nbsp;&nbsp;
        <input type="text" size="40" name="username"></input><br><br>
        <label>
Your Email:</label>&nbsp;&nbsp;
        <input type="text" size="40" name="email"></input><br><br>
        <input type="submit" name="submit" value="Submit results"></input>
    </form>

    </body>
</html>


Lab Activity #3:
Insert the form provided above into a page on your website.

Next, modify the JavaScript to check for the following conditions.  If any condition is not met, display an appropriate, descriptive message to the user and prevent further submission of the form.
Conditions:
  • the name field contains no less than 10 characters
  • the name field contains at least one space character
  • the email field contains no less than 10 characters
  • the email field contains at least one period character
Finally, add a pull-down menu item to the form listing codes for all 50 states.  Then, modify your validation function to check to see which state the user selects and add the following message depending on the state selected:
  1. if the state is 'VA' (Virginia), display "Hey, that's where Pete is from!',
  2. if the state is 'PA' (Pennsylvania), display "Hey, that's where John is from!', and
  3. if the state is 'TX' (Texas), display "Hey-y'all, that's where Nell is from!'.

12.5  More with JavaScript

To keep this lab short, we have had to remove a lot of material about JavaScript.  Because of this, we could do an entire series of labs just on JavaScript.  For example, we could talk all about the various data types in JavaScript, how you can modify the browser's status bar, how to import JavaScript from another source file, and on.  One area that needs a good deal of attention is how to script and support older browsers.  If you get into serious JavaScript development, you would definitely want to purse this topic even further.

This lab however, is only meant to be an introduction to the capabilities that JavaScript can bring to your web pages.  In the next lab, we will see additional uses of JavaScript, as we combine CSS and JavaScript to get Dynamic HTML (DHTML).  But, before we go, here are a few short tasks to complete regarding JavaScript.

Lab Activity #4:
Use the web to find the answers for the following questions.  Where appropriate list the web site URL.
  1. What is the (full) name of the organizing body that is working to standardize browser scripting languages? ____________________________________

  2. What is the web address of the organization mentioned in question #1? ___________________________________

  3. Locate a web site that provides a tutorial on JavaScript development.  What is its URL? __________________________________


About the labs:
These labs were developed in conjunction with the Jones and Bartlett textbook Computer Science Illuminated by Nell Dale and John Lewis.
ISBN:  0-7637-1760-6
Lab content developed by Pete DePasquale and John Lewis.
 
Educators: More Information About This Text Other Computer Science Titles at Jones and Bartlett
Copyright 2019 Jones and Bartlett PublishersContact webmaster