What is JavaScript?
JavaScript is Netscape's cross-platform, object-based scripting language
Client-side JavaScript is embedded directly in HTML pages and is interpreted by browser completely 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 JScript (version of JavaScript approximately 1.0-1.1)
JavaScript syntax much like Java, C, C++
JavaScript language resembles Java but does not have Java's static typing and strong type checking
JavaScript supports most Java 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 (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
String literal is zero or more characters enclosed in double (") or single (') quotation marks
Expression is any valid set of literals, 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
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
Defining function does not execute it. Must be called for it to do its work.
if...else Statement
(1) Build HTML dynamically
(2) Monitor user events and take actions --
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 number of JavaScript statements
<SCRIPT> JavaScript statements... </SCRIPT>Document can have multiple <SCRIPT> tags
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
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> <SCRIPT LANGUAGE="JavaScript"> <!-- Hide script from old browsers document.write ("My first JavaScript!"); // end script hiding from old browsers --> </SCRIPT> </HEAD> <BODY> 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)
<HEAD> <TITLE>My Page</TITLE> <SCRIPT SRC="common.js"> ... </SCRIPT> </HEAD>JavaScript statements within <SCRIPT> tag with SRC attribute are ignored unless inclusion has error
Using JavaScript Expressions as HTML Attribute Values
JavaScript entities start with ampersand (&) and end with semicolon (;)
JavaScript entities are interpreted only on right-hand side of HTML attribute name/value pairs
Use JavaScript expression enclosed in curly braces {}
Suppose you define variable barWidth
<HR WIDTH="&{barWidth};%" ALIGN=LEFT>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> 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, "><P>", text) } // end script hiding from old browsers --> </SCRIPT> </HEAD> <BODY> <H1>Using the write method</H1> <SCRIPT> <!--- hide script from old browsers rule(25); heading(2, "The write method", "Notice the use of + and ,"); // end script hiding from old browsers --> </SCRIPT> <P> This is some standard HTML, unlike the above that is generated.<P> </BODY>Try it
Using Client-Side 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 documentWindow 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
setInterval: evaluates expression or calls function each time specified period elapses
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 (inner height and width of browser window -- can be changed to resize window)
navigator object properties: appName (name of browser ... Netscape), appVersion (version information ... 4.06)
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