JavaScript

This document was last modified


Introduction

What is JavaScript?

JavaScript is Netscape's cross-platform, object-based scripting language

Netscape provides on-line JavaScript documentation

Client-side JavaScript is embedded directly in HTML pages and is interpreted by browser at runtime

Client-side JavaScript statements embedded in HTML page can respond to user events such as mouse-clicks, form input, and page navigation

JavaScript 1.1 (supported by Netscape 3.x)

JavaScript 1.2 (supported by Netscape 4.x)

Internet Explorer also supports JavaScript and JScript (Microsoft version of JavaScript)

JavaScript syntax much like Java, C, C++

JavaScript language resembles Java but does not have Java's static typing and strong type checking. That means you do not have to declare what type a variable is in JavaScript like you have to in Java.

JavaScript and Java have nearly same expression syntax and basic control-flow constructs

JavaScript -- Interpreted (not compiled) by client
Java -- Compiled bytecodes downloaded from server, executed on client

JavaScript -- Code integrated with, and embedded in, HTML
Java -- Applets distinct from HTML (but accessed from HTML pages)


JavaScript Basics

Values -- numbers (42, 3.14159), logical values (true, false), strings ("Purdue University")

Use variables as symbolic names for values. Must start with letter or underscore (_). Subsequent characters can also be digits (0-9).

Declare a variable via
var x;

Character string is zero, one, or more characters enclosed in double (") or single (') quotation marks

Expression is any valid set of values, variables, operators, and expressions that evaluates to single value; value can be number, string, or logical value

Basic assignment operator is equal (=)

Standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/)

Comparison operators are equal (==), not equal (!=), greater than (>), greater than or equal (>=), less than (<), less than or equal (<=)

JavaScript is object-based

Object has properties (fields)

Object has functions associated with it that are known as the object's methods

Function is JavaScript procedure -- set of statements that performs specific task

if...else Statement

if (condition) { statements1 } else { statements2 } if (form1.threeChar.value.length == 3) { return true; } else { alert("Enter exactly three characters. " + document.form1.threeChar.value + " is not valid."); return false; } switch Statement

switch (expression) { case label : statement; break; case label : statement; break; ... default : statement; } switch (fruit) { case "Oranges" : document.write("Oranges are $0.59 a pound.<BR>"); break; case "Apples" : document.write("Apples are $0.32 a pound.<BR>"); break; case "Bananas" : document.write("Bananas are $0.48 a pound.<BR>"); break; case "Cherries" : document.write("Cherries are $3.00 a pound.<BR>"); break; default : document.write("Sorry, we are out of " + fruit + ".<BR>"); } for Statement

for (initial; condition; increment) { statements } for (i=0; i < selectObj.options.length; i=i+1) { if (selectObj.options[i].selected==true) { numberSelected = numberSelected +1; } } while Statement

while (condition) { statements } n = 0; x = 0; while( n < 3 ) { n = n+1; x = x+n; } do...while Statement

do { statement } while (condition); do { i=i+1; document.write(i); } while (i<5);

What We Can Do with JavaScript

(1) Build HTML dynamically

(2) Monitor user events and take actions -- such as...
clicking button or link
changing form field
moving mouse on or off link


Embedding JavaScript in HTML

<SCRIPT> tag is extension to HTML that can enclose JavaScript statements

<SCRIPT>
   JavaScript statements...
</SCRIPT>
Document can have multiple <SCRIPT> tags and, thus, multiple groups of JavaScript statements

Netscape 3.0 executes code within
<SCRIPT LANGUAGE="JavaScript"> and
<SCRIPT LANGUAGE="JavaScript1.1"> tags; it ignores code within
<SCRIPT LANGUAGE="JavaScript1.2"> tag

Netscape 4.0 executes code for all three

Only Netscape 2.0 and later versions recognize JavaScript at all

To ensure that other browsers ignore JavaScript code, place entire script within HTML comment tags, and precede ending comment tag with double-slash (//) that indicates JavaScript single-line comment

<SCRIPT>
<!-- Hide script from old browsers
JavaScript statements...
// end script hiding from old browsers -->
</SCRIPT>
Simple script...

<HTML>
<HEAD>
<TITLE>My first JavaScript!</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from old browsers
document.write ("My first JavaScript!");
// end script hiding from old browsers -->
</SCRIPT>
JavaScript can be used to create text 
that is displayed along with
text appearing in the BODY of the file.
</BODY>
</HTML>
Try it

SRC attribute of <SCRIPT> tag lets you specify file as JavaScript source (rather than embedding JavaScript in HTML)

JavaScript statements within <SCRIPT> tag with SRC attribute are ignored unless inclusion has error

<HEAD>
<TITLE>My Page</TITLE>
<SCRIPT SRC="common.js">
document.write ("Oops.  
  Something went wrong in getting 
  the JavaScript file!");
</SCRIPT>
</HEAD>

Functions

Define functions for page in HEAD portion of document

JavaScript Calculator

<HEAD> 
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from old browsers
function increase (number) 
 {
   return (number + 1);
 }
// end script hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
   document.write("The function returned ", 
   increase(7), ".");
</SCRIPT>
<P> That is all.... <P>
</BODY>
Try it

write method of document displays output on screen

<HEAD> 
<SCRIPT LANGUAGE="JavaScript">
<!--- Hide script from old browsers

// This function displays a horizontal rule
// of specified width

function rule(width) 
 {
   document.write("<HR ALIGN=LEFT WIDTH=" 
   + width + "% NOSHADE>");
 }

// This function displays a heading 
// of specified level and some text

function heading(headLevel, headText, text) 
 {
   document.write("<H", headLevel, ">", 
      headText, "</H",
      headLevel, ">", text, "<P>")
 }
// end script hiding from old browsers -->
</SCRIPT>
</HEAD>

<BODY>
<H1>Using the write method</H1>
<SCRIPT LANGUAGE="JavaScript">
<!--- hide script from old browsers
rule(25);
heading(2, "The write method", 
  "Notice the use of + and ,");
// end script hiding from old browsers -->
</SCRIPT>
This is some standard HTML, 
unlike the above that is generated.<P>
</BODY>
Try it


Using JavaScript Objects

navigator: properties for name and version of Netscape being used

window: properties for entire window (also window object for each window in framed document)

document: properties for document content, such as title, background color, links, forms

To refer to specific properties, specify object name and all ancestors

Generally, object gets name from NAME attribute of corresponding HTML tag

document.sform.schoolname.value value property of schoolname text field in form named sform in current document


Window Methods

alert: displays an alert box with message

confirm: displays confirm dialog box with OK and Cancel buttons

prompt: displays prompt dialog box with text field for entering a value

If you want to know about Prompts, well then <SCRIPT LANGUAGE="JavaScript"> document.write(prompt("Enter your name:", "Justin")); </SCRIPT> this page is for you! JavaScript prompt

JavaScript confirmation

setTimeout: evaluates expression or calls function once after specified period elapses (in milliseconds -- thousandths of seconds)

setInterval: evaluates expression or calls function each time specified period elapses (in milliseconds)

location: redirects client to another URL as if user had clicked hyperlink

location = "http://www.purdue.edu"; Pick and Click with Javascript

document object properties: title, bgColor, fgColor, linkColor, alinkColor, vlinkColor, lastModified (date document was last modified), referrer (previous URL client visited), and URL (URL of document)

window object properties: innerHeight, innerWidth, outerHeight, outerWidth (inner and outer height and width of browser window -- can be changed to resize window)

navigator object properties: appName (name of browser ... Netscape), appVersion (version information ... 4.05)

document.topform document.fillform document.lastform Form objects stored in array called forms

document.forms[0] document.forms[1] document.forms[2] Elements in form (text fields, radio buttons, etc.) also stored in elements array

document.forms[1].elements[3] Also arrays for document.applets, document.images, document.links, window.frames

Using form arrays

document.writeln("Title --", document.title, "<BR>"); document.writeln("URL --", document.URL, "<BR>"); document.writeln("Background color --", document.bgColor, "<BR>"); document.writeln("Last Modified --", document.lastModified, "<BR>"); document.writeln("Referred by --", document.referrer, "<BR>"); document.writeln("Inner height of window --", window.innerHeight, "<BR>"); document.writeln("Inner width of window --", window.innerWidth, "<BR>"); document.writeln("Outer height of window --", window.outerHeight, "<BR>"); document.writeln("Outer width of window --", window.outerWidth, "<BR>"); document.writeln("Web browser is --", navigator.appName); document.writeln(" version ", navigator.appVersion, "<BR>"); Try it

window.innerWidth=450; window.innerHeight=250; Try it


Handling Events

Events are actions that occur usually as result of something user does --
clicking button or link
changing form field
moving mouse on or off link

Event handlers and events:

onFocus - user gives input focus to window or form element
onBlur - user removes input focus from window or form element

onChange - user changes text field, textarea, select list

onClick - user clicks button or link

onMouseOver - user moves cursor over link

onMouseOut - user moves cursor out of client-side image map or link

onSubmit - user submits form

<TAG eventHandler="JavaScript Code">
where TAG is HTML tag, eventHandler is name of the event handler, JavaScript Code is function call (usually) or JavaScript statements

<INPUT TYPE="button" VALUE="Calculate" 
onClick="compute(this.form)">
this refers to current object -- the button
this.form refers to form containing the button

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from old browsers

function compute(fm) 
 {
   if (confirm("Is this what you want?"))
      fm.result.value = eval(fm.expr.value)
   else
      setInterval
      ('alert("Please try again!")',10000)
 }

// end script hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Enter some expression:
<INPUT TYPE="text" NAME="expr" SIZE=15>
<INPUT TYPE="button" VALUE="Calculate"
onClick="compute(this.form)">
<BR>
Result:
<INPUT TYPE="text" NAME="result" SIZE=15>
</FORM>
</BODY>
Try it

OnMouseOver can also be used for changing images and popping up alerts


Validating Form Input

As user enters it, with onChange event handler on each form element that you want validated

When user submits form, with onClick event handler on button that submits form

<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from old browsers

function foc() 
 {
   status="Please enter a number 1-999";
 }

function blu() 
 {
   status="";
 }

function isaPosNum(s) 
 {
   return (parseInt(s) > 0)
 }

function qty_check(item, min, max) 
 {
   var returnVal = false
   if (!isaPosNum(item.value)) 
      alert("Please enter a positive number")
   else if (parseInt(item.value) < min) 
      alert("Please enter a " + item.name 
            + " greater than " + min)
   else if (parseInt(item.value) > max) 
      alert("Please enter a " + item.name 
            + " less than " + max)
   else 
      returnVal = true
   return returnVal
 }

function validateAndSubmit(theform) 
 {
   if (qty_check(theform.quantity, 0, 999)) 
   {
      alert("Order has been Submitted")
      return true
   }
   else 
   {
      alert
        ("Sorry, Order Cannot Be Submitted!")
      return false
   }
}

// end script hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<H1>Validating Form Input</H1>

<FORM ACTION="lwapp.cgi" METHOD="post">
Quantity of tennis balls?
<INPUT TYPE="text" NAME="quantity" 
onFocus="foc()"
onBlur="blu()"
onChange="qty_check(this, 0, 999)">
<BR> 
<INPUT TYPE="button" VALUE="Enter Order" 
onClick="validateAndSubmit(this.form)">
</FORM>
</BODY>
Try it


Using Windows and Frames

Can create a window with the open method

colorWindow=window.open("color.html") Can specify attributes such as window's height and width and whether window contains toolbar, location field, or scrollbars

purdueWindow=window.open ("http://www.purdue.edu", "purduePlace", "height=300,width=500,location=yes, toolbar=no,scrollbars=yes") Try it

function Navigator() { myWin= open("Navigation.html", "displayWindow", "width=250,height=120,status=no, toolbar=no,menubar=no"); } <BODY BGCOLOR="#000000" OnLoad="Navigator()"> Try it


Creating a Frame

<FRAMESET ROWS="90%,10%"> <FRAMESET COLS="30%,70%"> <FRAME SRC=category.html NAME="listFrame"> <FRAME SRC=titles.html NAME="contentFrame"> </FRAMESET> <FRAME SRC=navigate.html NAME="navigateFrame"> </FRAMESET> listFrame is top.frames[0]
contentFrame is top.frames[1]
navigateFrame is top.frames[2]

function reframe() { top.frames[0].location='inter.title.html'; top.frames[1].location='inter.toc.html'; top.frames[2].location='titlePage.html'; } <INPUT TYPE="button" VALUE="The Internet" onClick="reframe()"> Try it


Using JavaScript URLs

function visit() { if (confirm ("Would you like to visit Purdue?")) purdueWindow=window.open ("http://www.purdue.edu", "purduePlace", "height=300,width=500,location=yes, toolbar=no,scrollbars=yes") else alert("Maybe next time...") } This page can open a new window containing the <A HREF="javascript:visit()"> Purdue Website</A>....<P> Try it


Using the Status Bar

Two window properties display messages in the Netscape status bar

defaultStatus appears when nothing else is in status bar

status displays transient message in status bar

<SCRIPT LANGUAGE="JavaScript"> <!-- Hide script from old browsers defaultStatus = "Watch this status line as you move the mouse over the image map"; // end script hiding from old browsers --> </SCRIPT> <AREA SHAPE="RECT" COORDS="26,72,145,146" HREF="http://www.nbc.com/" onMouseOver="status='Go to NBC'; return true" onMouseOut="status='Do not go to NBC!'; return true"> Try it