Client-Side JavaScript

This course describes the practical uses of client-side JavaScript. Client-Side refers to actions that take place on the remote browser without any interaction with the server.

  1. JavaScript is not Java
  2. Adding JavaScript to an HTML Document
    1. Basic HTML Skeleton
    2. Using the <script>...</script> tag in HTML
    3. Hiding JavaScript from Older Browsers
    4. JavaScript in the <head>...</head> and <body>...</body> tags
    5. Specifying a Specific JavaScript Version
    6. Referring to an External JavaScript Files
  3. JavaScript Variables
    1. Assigning Values to JavaScript Variables
    2. Case Sensitivity
    3. Variables Scope
    4. Array Variables
  4. JavaScript Functions
  5. Events
    1. Common Browser Events
    2. Triggering a JavaScript Function using an Event
    3. Executing a JavaScript Function when a page is opened
  6. Conditional Constructs
  7. Referencing HTML Form Controls within JavaScript
  8. Building and Testing Your Forms
  9. Identifying and Fixing Programming Errors
    1. Using Netscape
    2. Using Internet Explorer
  10. More Applications for JavaScript in HTML Documents
    1. Working with Dates
    2. Keystroke Events
    3. Mouse-Over Roll-Over Images
    4. On-the-fly Form Field Modification
    5. Form Field Validation
  11. JavaScript Documentation Resources
    1. Netscape Documents - (HTML PDF)
    2. JavaScript Windows Help Documents
  12. Where can I learn more about JavaScript

1.0  JavaScript is NOT Java

The following is an excerpt from Danny Goodman's JavaScript Pages

It is amazing how many people, including industry insiders, don't understand the difference between Java and JavaScript. Here's the low-down.

Java, developed under the Sun Microsystems brand, is a full-fledged object-oriented programming language. It can be used to create standalone applications and a special type of mini application, called an applet. Applets are downloaded as separate files to your browser alongside an HTML document, and provide an infinite variety of added functionality to the Web site you are visiting. The displayed results of applets can appear to be embedded in an HTML page (e.g., the scrolling banner message that is so common on Java-enhanced sites), but the Java code arrives as a separate file.

JavaScript, developed by Netscape, is a smaller language that does not create applets or standalone applications. In its most common form today, JavaScript resides inside HTML documents, and can provide levels of interactivity far beyond typically flat HTML pages -- without the need for server-based CGI (Common Gateway Interface) programs.

Some server software, such as Netscape's SuiteSpot, lets web application developers write CGI programs in a server-side version of JavaScript. Both client-side and server-side JavaScript share the same core JavaScript language, but each side deals with different kinds of objects. Client-side objects are predominantly the components of an HTML web page (e.g., forms, text boxes, buttons). Server-side objects are those that facilitate the handling of requests that come from clients, as well as connectivity to databases.

It is important to understand that a Java-enabled browser is not automatically a JavaScript-enabled browser: the two technologies require entirely separate interpreters (licensed from separate companies) to handle the languages. It is unlikely, however, that future browsers will incorporate one but not the other (plus or minus implementation timetables on various platforms).

Starting with Netscape Navigator 3.0, HTML authors have been able to use JavaScript to link HTML form elements to Java applets (and plug-ins) or link Java applets to each other--LiveConnect(tm), Netscape calls this technology. Rather than competing with each other, Java and JavaScript are a powerful combination.

Much simpler and smaller than the Java vocabulary, JavaScript is within reach of authors who know HTML; writing full-fledged Java, on the other hand, benefits from experience with C and C++. Java and JavaScript share a number of vocabulary and syntax constructions, but the languages are intended for very different purposes.

All you need to program in JavaScript is a text editor and a JavaScript-enabled browser, such as Netscape Navigator 4+ or Internet Explorer 4+.


2  Adding JavaScript to an HTML Document back to ToC

Basic HTML Skeleton


     Try it!

Using the <script>...</script> tag in HTML

Add a JavaScript block to an HTML document by inserting the 'script' tags as shown below on lines 6 and 8.


     Try it!

Hiding JavaScript from Older Browsers

Hide JavaScript code from older browsers by using the comment tags as shown below on lines 7 and 9. This prevents the non-JavaScript browser from print the code to the screen.


     Try it!

JavaScript in the <head>...</head> and <body>...</body> tags

JavaScript code blocks can be used inside of the <head>...</head> tags and/or <body>...</body> tags. Typically, JavaScript code blocks in the document head are used to define/initialize variables and define functions. JavaScript code blocks in the document body are used to execute functions and print information on the screen.


     Try it!

Specifying the JavaScript Version

By default the script tag should state that the block is a JavaScript. By not specifying a JavaScript version, the browser will try to execute the code. In older browser versions this may cause JavaScript error messages to be displayed.

   <SCRIPT LANGUAGE="JavaScript" type="text/javascript">

If the JavaScript code you write uses features specific to a JavaScript version, or you want to make sure your code functions in older browser versions, you will have to specify a specific JavaScript version in the script tags. You will then have to provide separate script segments for each version of JavaScript you wish to support.

   <SCRIPT LANGUAGE="JavaScript1.2" type="text/javascript">

Including (or referring to) an External JavaScript File

Not all JavaScript source code must be embedded in the HTML document. If you have written a module or library of functions and wish to make them available in your HTML document you can include the external JavaScript code by specifying the 'src' attribute in the script tag. The 'src' must be a valid path (absolute or relative) and file name. Typically JavaScript files have an extension of '.js'.

   <script
     language="JavaScript"
     type="text/javascript"
     src="../javascripts/someJavaScriptFile.js">
   </script>

3  JavaScript Variables back to ToC

Assigning Values to JavaScript Variables

JavaScript variables are "loosely-typed", meaning a variable can hold most any type of value, such as strings, integers, floating point, and Boolean values. Variables are defined with or without using the 'var' initializer. Variable names can contain letters, numbers and underscore (_), and must start with either a letter or the underscore (_) character.


     Try it!

Case Sensitivity

JavaScript variables are case-sensitive All of the definitions in the example below refer to unique variable names.


Variables Scope

Variables defined outside a function are global in scope and can be accessed from any function in the document. Variables defined inside a function are local in scope and created and destroyed with function execution. Local variables can only be accessed from within the function they are defined.


     Try it!

Array Variables

JavaScript Array variables are single-column collections of ordered data. Array variable can store any combination of strings, numbers for objects. Array values are accessed by integer indexes. The code snippet below shows the various ways arrays can be initialized


The number of elements in the array can be determined using the 'length' attribute of the array variable.


     Try it!

For more detailed information on JavaScript arrays see Danny Goodman's Primer on JavaScript Arrays

4  JavaScript Functions back to ToC

JavaScript functions are defined in the document head, and can be called from anywhere in the document head or document body. Functions can accept one or more arguments and can return a result. The result can be any variable type, array, or object. In the example below two functions are defined, one to convert Fahrenheit to Celsius and one to control the format (number of decimal places) of a number. The example also includes the use of some intrinsic JavaScript Objects (Math.pow) and functions (parseInt)


     Try it!

5  Events back to ToC

Common Browser Events

JavaScript functions can be triggered to execute by events. Events are interrupts the operating system sends the browser when; keyboard is pressed or the mouse is moved or clicked. Some examples of events are described in the table below:

Common Browser Event Descriptions
Event NameDescription
OnBlurOccurs when an object looses focus
OnClickOccurs when the mouse clicks on the object
OnDblClickOccurs when the mouse double-clicks on the object
OnFocusOccurs when the object gets focus. Either by mouse click or keyboard shortcut, or tabbing
OnKeyDownOccurs when any key is pressed, on the down-stroke.
OnKeyPressOccurs when any key is pressed, on the up-stroke.
OnKeyUpOccurs when any key is pressed, on the up-stroke.
OnMouseDownOccurs when the mouse key is pressed, on the down-stroke.
OnMouseUpOccurs when the mouse key is pressed, on the up-stroke.
OnMouseOverOccurs when the mouse's position is moved over the object
OnMouseOutOccurs when the mouse's position is moved off of the object
OnMouseMoveOccurs when the mouse is moved.
onSubmitThe onsubmit event occurs when a form is submitted. It only applies to the FORM element.
onResetThe onreset event occurs when a form is reset. It only applies to the FORM element.
onSelectThe onselect event occurs when a user selects some text in a text field. This attribute may be used with the INPUT and TEXTAREA elements.
onChangeThe onchange event occurs when a control loses the input focus and its value has been modified since gaining focus. This attribute applies to the following elements: INPUT, SELECT, and TEXTAREA.

Triggering a JavaScript Function using an Event

Below is an example of browser event processing:


     Try it!

Executing a JavaScript Function when a page is opened

This example demonstrates how the OnLoad event used in conjunction with the body tag can be used to execute JavaScript code automatically.


     Try it!

6  Conditional Constructs back to ToC

JavaScript provides the standard Conditional Constructs including if-else statements, for-loops, and while-loops. The example below demonstrates the syntax of these constructs.


     Try it!

7  Referencing HTML Form Controls within JavaScript back to ToC

The example below demonstrates how to reference HTML form elements using JavaScript. The example expands on the Fahrenheit to Celsius code discussed above and turns the page from a static display to an interactive page.


     Try it!

8  Building and Testing Your Forms back to ToC

If you are building a form and want to test it you can use my FormTest.jsp. This JSP will display the parameters your form sent, and allow you to examine how various form elements submit information. The URL of the form tester is:

http://www.profiler.noaa.gov/jsp/FormTester.jsp

Open an Example form to see how it works.

9  Identifying and Fixing Programming Errors back to ToC

Using Netscape

JavaScript error in an HTML page show up in the NetScape browser at the bottom of the screen in the status area. You will see a message similar to the following:

If you type 'javascript:' into the address box a detailed error message dialog is displayed as shown below. The message box will indicate the offending line number, and you can go back to your source code a fix the error.

Using Internet Explorer

JavaScript error in an HTML page show up in the Internet Explorer browser at the bottom left of the screen as a yellow triangle (see Figure below)

If you double-click on the icon, a detailed error message dialog is displayed as shown below. The message box will indicate the offending line number, and you can go back to your source code a fix the error.

10  More Applications for JavaScript in HTML Documents back to ToC

Working with Dates


     Try it!

Keystroke Events


     Try it!

Mouse-Over Roll-Over Images

     Try it!

On-the-fly Form Field Modification

This example shows how JavaScript can be used to dynamically modify the contents of <form> controls and give controls the ability to interact with one-another. This example uses Date and String Objects and demonstrates many of their intrinsic methods.

     Open Dynamic Form Example

The Dynamic Form Example has a bug in this code, for some home work, why don't you try to figure out what the bug is and how to fix it!

Form Field Validation

Form field validation allows the client application to check for gross-error in a form's data prior to submitting the data to the server. To keep things short, lets look at a simple example of form validation.

Form Validation Example
     Try it!

Netscape has an excellent library of JavaScript Form Validation code that does a variety of validations. Download javaScriptFormValidation.zip and take a look at the documentation to see how you might be able in incorporate it into your pages. Here are some examples of the library functions

SUMMARY

This is a set of JavaScript functions for validating input on 
an HTML form.  Functions are provided to validate:

     - U.S. and international phone/fax numbers
     - U.S. ZIP codes (5 or 9 digit postal codes)
     - U.S. Postal Codes (2 letter abbreviations for names of states)
     - U.S. Social Security Numbers (abbreviated as SSNs)
     - email addresses
	- dates (entry of year, month, and day and validity of combined date)
	- credit card numbers

Supporting utility functions validate that:

     - characters are Letter, Digit, or Letter Or Digit
     - strings are a Signed, Positive, Negative, Nonpositive, or
       Nonnegative integer
     - strings are a Float or a Signed Float
     - strings are Alphabetic, Alphanumeric, or Whitespace
     - strings contain an integer within a specified range

Functions are also provided to interactively check the
above kinds of data and prompt the user if they have
been entered incorrectly.

Other utility functions are provided to:

	- remove from a string characters which are/are not 
	  in a "bag" of selected characters	
	- reformat a string, adding delimiter characters
	- strip whitespace/leading whitespace from a string
    - reformat U.S. phone numbers, ZIP codes, and Social
      Security numbers


Many of the below functions take an optional parameter eok (for "emptyOK")
which determines whether the empty string will return true or false.
Default behavior is controlled by global variable defaultEmptyOK.

BASIC DATA VALIDATION FUNCTIONS:

isWhitespace (s)                    Check whether string s is empty or whitespace.
isLetter (c)                        Check whether character c is an English letter 
isDigit (c)                         Check whether character c is a digit 
isLetterOrDigit (c)                 Check whether character c is a letter or digit.
isInteger (s [,eok])                True if all characters in string s are numbers.
isSignedInteger (s [,eok])          True if all characters in string s are numbers; leading + or - allowed.
isPositiveInteger (s [,eok])        True if string s is an integer > 0.
isNonnegativeInteger (s [,eok])     True if string s is an integer >= 0.
isNegativeInteger (s [,eok])        True if s is an integer < 0.
isNonpositiveInteger (s [,eok])     True if s is an integer <= 0.
isFloat (s [,eok])                  True if string s is an unsigned floating point (real) number. (Integers also OK.)
isSignedFloat (s [,eok])            True if string s is a floating point number; leading + or - allowed. (Integers also OK.)
isAlphabetic (s [,eok])             True if string s is English letters 
isAlphanumeric (s [,eok])           True if string s is English letters and numbers only.

isSSN (s [,eok])                    True if string s is a valid U.S. Social Security Number.
isUSPhoneNumber (s [,eok])          True if string s is a valid U.S. Phone Number. 
isInternationalPhoneNumber (s [,eok]) True if string s is a valid international phone number.
isZIPCode (s [,eok])                True if string s is a valid U.S. ZIP code.
isStateCode (s [,eok])              True if string s is a valid U.S. Postal Code
isEmail (s [,eok])                  True if string s is a valid email address.
isYear (s [,eok])                   True if string s is a valid Year number.
isIntegerInRange (s, a, b [,eok])   True if string s is an integer between a and b, inclusive.
isMonth (s [,eok])                  True if string s is a valid month between 1 and 12.
isDay (s [,eok])                    True if string s is a valid day between 1 and 31.
daysInFebruary (year)               Returns number of days in February of that year.
isDate (year, month, day)           True if string arguments form a valid date.


FUNCTIONS TO REFORMAT DATA:

stripCharsInBag (s, bag)            Removes all characters in string bag from string s.
stripCharsNotInBag (s, bag)         Removes all characters NOT in string bag from string s.
stripWhitespace (s)                 Removes all whitespace characters from s.
stripInitialWhitespace (s)          Removes initial (leading) whitespace characters from s.
reformat (TARGETSTRING, STRING,     Function for inserting formatting characters or
  INTEGER, STRING, INTEGER ... )       delimiters into TARGETSTRING.                                       
reformatZIPCode (ZIPString)         If 9 digits, inserts separator hyphen.
reformatSSN (SSN)                   Reformats as 123-45-6789.
reformatUSPhone (USPhone)           Reformats as (123) 456-789.


FUNCTIONS TO PROMPT USER:

prompt (s)                          Display prompt string s in status bar.
promptEntry (s)                     Display data entry prompt string s in status bar.
warnEmpty (theField, s)             Notify user that required field theField is empty.
warnInvalid (theField, s)           Notify user that contents of field theField are invalid.


FUNCTIONS TO INTERACTIVELY CHECK FIELD CONTENTS:

checkString (theField, s [,eok])    Check that theField.value is not empty or all whitespace.
checkStateCode (theField)           Check that theField.value is a valid U.S. state code.
checkZIPCode (theField [,eok])      Check that theField.value is a valid ZIP code.
checkUSPhone (theField [,eok])      Check that theField.value is a valid US Phone.
checkInternationalPhone (theField [,eok])  Check that theField.value is a valid International Phone.
checkEmail (theField [,eok])        Check that theField.value is a valid Email.
checkSSN (theField [,eok])          Check that theField.value is a valid SSN.
checkYear (theField [,eok])         Check that theField.value is a valid Year.
checkMonth (theField [,eok])        Check that theField.value is a valid Month.
checkDay (theField [,eok])          Check that theField.value is a valid Day.
checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
                                    Check that field values form a valid date.
getRadioButtonValue (radio)         Get checked value from radio button.
checkCreditCard (radio, theField)   Validate credit card info.


CREDIT CARD DATA VALIDATION FUNCTIONS

isCreditCard (st)              True if credit card number passes the Luhn Mod-10 test.
isVisa (cc)                    True if string cc is a valid VISA number.
isMasterCard (cc)              True if string cc is a valid MasterCard number.
isAmericanExpress (cc)         True if string cc is a valid American Express number.
isDinersClub (cc)              True if string cc is a valid Diner's Club number.
isCarteBlanche (cc)            True if string cc is a valid Carte Blanche number.
isDiscover (cc)                True if string cc is a valid Discover card number.
isEnRoute (cc)                 True if string cc is a valid enRoute card number.
isJCB (cc)                     True if string cc is a valid JCB card number.
isAnyCard (cc)                 True if string cc is a valid card number for any of the accepted types.
isCardMatch (Type, Number)     True if Number is valid for credic card of type Type.

Other stub functions are retained for backward compatibility with LivePayment code.
See comments below for details.

Performance hint: when you deploy this file on your website, strip out the
comment lines from the source code as well as any of the functions which
you don't need.  This will give you a smaller .js file and achieve faster
downloads.

18 Feb 97 created Eric Krock

(c) 1997 Netscape Communications Corporation

11  JavaScript Documentation Resources back to ToC

Netscape Documents - (HTML PDF)

http://developer.netscape.com/docs/manuals/javascript.html

JavaScript Windows Help Documents

This is an excellent resource for Windows Users. This a JavaScript Windows Help File that you can download and put on your PC. The biggest advantage of this is the ability to search for words in the documentation. A sample screen shot is shown below;

http://www.confluent.fr/javadoc/javascripte.html

Or get a zipped copy of jsref13.zip from me.

Windows Help Screen Capture

12  Where can I learn more about JavaScript back to ToC

JavaScript Tutorials http://javascriptkit.com/javaindex.shtml
JavaScript Articles http://tech.irt.org/articles/script.htm
JavaScript for Beginners http://www.javascriptmall.com/learn/contents.htm
JavaScript Examples http://www.w3schools.com/js/js_examples.asp
JavaScript Tutorial for Programmers http://www.wdvl.com/Authoring/JavaScript/Tutorial/
JavaScript Tutorials http://www.pageresource.com/jscript/index4.htm
JavaScript Tutorial http://www.cs.brown.edu/courses/bridge/1998/res/javascript/javascript-tutorial.html#4
Doctor JavaScript http://www.webreference.com/js/
JavaScript Toolkits http://www.mattkruse.com/javascript/date/
JavaScript Julian Date Goodies http://zijlema.basicguru.com/javascript.html
Julian Day Calulator http://www.starlightccd.com/walter/bytebook/javascript/jdcalc.htm
Netscape's Developers Web Site http://developer.netscape.com/