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
function
keyword
if...else Statement
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
<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
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
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
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)
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 buttonthis.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
Creating a Frame
listFrame
is top.frames[0] contentFrame
is top.frames[1] navigateFrame
is top.frames[2]
Using JavaScript URLs
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