Title: JavaScript: Browser Programming
1JavaScript Browser Programming
- Marek Podgorny, EECS, Syracuse University, and
CollabWorx
2Outline
- Java vs. JavaScript, Interpreters vs. Compilers
- JavaScript Basics and Syntax
- JavaScript and Document Object Model
- JavaScript Methods
- JavaScript and HTML reflection
3General Remarks
- JavaScript is a web scripting language for
browsers - Invented by Netscape and innovated by Microsoft
- Standardized as ECMA language
- Netscape server-side JavaScript exists (Livewire)
but obsolete - JavaScript facilitates rapid prototyping of Web
pages and it takes load off the the server - Particularly useful for processing HTML forms
- JavaScript is also enabler of DHTML
- References JavaScript, The Definitive Guide by
David Flanagan (OReilly, 1998) The JavaScript
Bible by Danny Goodman (IDG, 1998) Dynamic HTML,
The Definitive Reference by Danny Goodman
(OReilly, 1998).
4Why would you use JavaScript?
- Typically JavaScript is invoked from HTML
- HTML text and JavaScript text are intertwined
- JavaScript allows you to modify Web page after it
was downloaded form server - If you need to make a dynamic page from C,
Perl, or Java you must write the HTML from these
languages - You can invoke applets from HTML but HTML and
applet actions are (typically) not linked - HTML and JavaScript are closely linked
- JavaScript can be seen as API to the browser
- This is since JavaScript can interact with
browser objects
5Java vs. JavaScript I
- Suns Java is fast becoming a broad industry
standard - Java is well designed and documented
- Java is object-oriented with (single) inheritance
- Java is class-based
- JavaScript is primarily supported by Netscape and
Microsoft - JavaScript started quite roughly but is
improving in design -- however some issues
connected to browser are totally ill defined as
browser ill defined -- e.g. what happens in what
order when frames loaded . - JavaScript is object-based with no class
structure - JavaScript is prototype-based
6Java vs. JavaScript (2)
- Java classes and instances are distinct
- A Java class has zero or more constructors
- Java property inheritance follows class hierarchy
- In Java, no way to add properties at run-time
- JS object definition and constructor are
identical and defined like methods - JavaScript property inheritance follows prototype
chain - JavaScript properties may be added or removed at
run-time - So essentially in JS, class structure is totally
dynamic (a.k.a. Ill defined)
7Java vs. JavaScript (3)
- Java applets are distinct from HTML
- Java is strongly typed with static (compile-time)
binding - Java bytecode is interpreted (or Just-In-Time
compiled) on the client
- JavaScript is tightly coupled with HTML
- JavaScript is loosely typed with dynamic
(run-time) binding - High-level JavaScript source code is interpreted
on the client but is often MUCH faster than Java
as integrated into browser
8Java vs. JavaScript (4)
- Java applet deployment cycle
- Java source --gt javac compiler --gt JavaVM
Universal Machine code in .class file - Store JavaVM .class files on Web Server
- Download JavaVM from Server to Client
- Interpreter built into browser, reads JavaVM and
executes on client - Java event handlers interpret events within
applet - JavaScript cycle
- JavaScript Source is included in HTML text or
special .js files included in HTML files - Combined JavaScript and HTML is downloaded and
interpreted by browser on client to produce HTML
Page - Events in HTML Page (mouse clicks etc.) are
either interpreted by browser default or
overridden by user JavaScript code
9JavaScript Version History
- JavaScript 1.0 debuted in NN 2.0 (Feb 96)
- JavaScript 1.1 appeared in NN 3.0
- NN 4.0 (a.k.a. Communicator) supports JavaScript
1.2 - MSIE 3.0 introduced JScript 2.0, a subset of
JavaScript 1.1 - JScript 3.x is supported in MSIE 4.0
- JScript 3.0 and later from IE are ECMA-compliant
Standard ECMA-262, June 1997 as is JavaScript
1.1 and following versions from Netscape - JavaScript 1.3 and 1.4 released with modest
changes including better exception handling and
Java-JavaScript linkage
10JavaScript 1.2
- Version 1.2 is the first one worth using
- New features in JavaScript 1.2 (NN4.0)
- Event object and event capturing
- Ten new event handlers
- Nested functions new Number() and String()
functions - New statements switch and dowhile
- Many new methods and properties (especially for
Window, String, and Array objects) - Perl4-compatible regular expressions
- Signed script security model
11JScript 3.1
- JScript 3.1 was released with MS IE v. 4.0
- Conditional execution (meta-statements)
- New event handlers (39 in all!)
- New statements switch and dowhile
- Two new identity operators ( and !) which
insist on variable types matching (default is to
convert types in and !) - Perl4-compatible regular expressions
- Debugger support
- Adequate documentation is lacking, however
12ECMAScript
- ECMAScript refers to standard ECMA-262 released
in June 1997 - Netscape site has ECMAScript standard document
- ECMAScript is essentially a definition of
JavaScript as programming language, without
reference to DOM - Meaning is the language and not the browser AWT
handler - Both Netscape and Microsoft versions are
ECMA-compliant but nevertheless mutually
incompatible - The HTML and emerging XML Document Object Models
(DOMs) will be bound initially to ECMAScript - Hence, one can use ECMAScript in several
different domains (HTML, XML, VRML ) by adding
support for appropriate domain specific DOMs
13JavaScript Basics
14JavaScript and HTML
- ltSCRIPT language"javascript"gt
- document.write("This document was last modified
on ") - document.write(document.lastModified)
- lt/SCRIPTgt
- This example illustrates a few key points
- JavaScript source code can be placed inline with
HTML code, contained within the ltSCRIPTgt
and lt/SCRIPTgt tags - JavaScript uses the dot (.) character for object
structures - An object may have properties (document.lastModifi
ed) and methods (document.write) - JavaScript has many built-in variables and
functions for interacting with web page content.
15JavaScript and HTML
- Besides scripts, JavaScript code can be placed in
HTML tags to define event handlers - ltFORMgt
- ltINPUT type"button" value"Push Me"
onClick"alert(Thank you very much)"gt - lt/FORMgt
- This HTML creates a button in a form
- The mouse click event handler for the button is a
single JavaScript statement that displays an
alert box with a message - The statement could also be a call to a function
you wrote to provide a more useful response
16JavaScript URLs
- ltA HREF"JavaScriptJumpTo(dest)"gt Go now! lt/Agt
- This HTML creates a link that looks like a normal
hyperlink - Clicking it runs a JavaScript function called
JumpTo, and passes it an argument dest which is
presumably a variable that was set by a previous
button click or other interaction with the user - The JavaScriptsomeStatement notation can be used
anywhere a normal URL can go - Try interactive console!
17JavaScript URLs
- A trivial example of a JavaScript URL
isjavascriptalert("Hello World!") - A JavaScript URL may appear anywhere an ordinary
URL is expectedltA HREF"javascripthistory.back(
)"gtPrevious Pagelt/Agt - Note must use ltA HREFjavascript
void(anyoldfunction())gt if you do not want link
to be invoked! - Use HREFjavascript void(0) if no action at
all -- used if real action from onclick or other
event handle for link - Navigator even has a mini-scripting environment
invoked by typing javascript into the browsers
location text field - This is used to display error messages as a
console instead of alternative (and clumsy)
stream of windows (one per error .)
18Loading scripts from files
- ltSCRIPT SRC"http//mywebsite.com/myfile.js"gt
- alert("Error loading script file.")
- lt/SCRIPTgt
- Please note the alert function that only fires if
browser fails to execute the script - Good methodology to store reusable scripts
- An external file must have a .js extension and
the server must be configured properly
19The ltSCRIPTgt Tag
- If you have two versions of a JavaScript script,
you can load one or the other - ltSCRIPT LANGUAGE"JavaScript1.1"gt
- // Ignored by Navigator 2.0 and higher
- location.replace("newVersion.html")
- lt/SCRIPTgt
- ltSCRIPT LANGUAGE"JavaScript"gt
- // Read by Navigator 2.0 and above
- lt/SCRIPTgt
20The ltSCRIPTgt Tag (contd)
- Multiple ltSCRIPTgt tags are allowed
- Within a single ltSCRIPTgt, a function may be
called before it is defined - Within a single document, a function defined in
one ltSCRIPTgt may not be called from a previous
ltSCRIPTgt - In particular, a function defined in the ltBODYgt
may not be called from the ltHEADgt
21Data types and declarations
- Numbers, strings, true, false, null, and
undefined values are known as primitive values - Anything else is an object!
- Assigning a primitive to a variable makes a copy,
assigning an object makes a reference! - Some objects return primitive values those that
dont, return the object string
22Variables
- Variable is an entity containing data
- Variable name must start from a letter or _
- JavaScript is case-sensitive! but has no fixed
type. - Variable scope
- A variable declared inside a function definition
using the var keyword, is local to that function - Variables that are not declared inside a
function, or that are declared without the var
keyword, are global! - A helpful practice is to place all global
variable declarations in the ltHEADgt section of
the HTML - One can reference variables in other windows via
win.var syntax
23Arrays
- Array type is provided for ordered sets of data
- Array indexes are represented by expressions in
square brackets, such as item50 - The Array object provides a number of methods for
rearranging and converting arrays - a new Array(10)
- regionNamenew Array("North", "Central", "South")
- regionName.length 3
- row1 new Array(3)
- row2 new Array(3)
- row3 new Array(3)
- grid new Array(row1, row2, row3)
24Arrays with String Indexes
- var person new Array()
- person"firstName" "Mary"
- person"lastName" "Jones"
- person"zipCode" 12345
- Arrays with numerical and string indexes are
treated separately! person.length 0 - personfirstName is equivalent to
person.firstname - Ergo, associative arrays are actually objects!
25Objects, Properties Methods
- In JavaScript, an object is a structured set of
data items, called properties, and code
(functions), called methods - var person new Array()
- person.firstName "Mary"
- person.lastName "Jones"
- person.age 34
- Internally, there is no difference between an
object and an associative array - However, it is rather inelegant to do it this way
26Constructors
- A clearer approach is to write a constructor
function for the object, and use the constructor
with the new operator - function person(first, last, yrs)
- this.firstName first
- this.lastName last
- this.age yrs
-
- var Mary new person("Mary", "Jones", 34)
- var Bob new person("Bob", "Lee", 27)
Note use of this to access the object by which
function is called!
Name of the class this is as close as
JavaScript gets to the concept of classes
27On the fly constructors
- var girl firstName"Sally", lastName"Forth",
age16 - These expressions can be nested, as in
- var family
- dadfirstName"George", lastName"Jones",
age58, - mom firstName"Martha", lastName"Forth",
age42, - numKids 2.7
-
28Built-in object types (DOM!)
All these object types can be used in constructors
29External Object
- External object types cannot be used in
constructors - Browser provides these objects as needed,
either as a result of reflection process, or the
objects are simply there - Anchor, Applet, Area, Button, Checkbox,
FileUpload, Form, Frame, Hidden, Link, MimeType,
Password, Plugin, Radio, Reset, Select, Submit,
Text, Textarea - We will discuss some of these deeper
30Values References
- Unlike primitive values, objects are manipulated
by references - A reference is a pointer or label that specifies
where some actual values are stored - var p1 new person("George", "Smith", 42)
- p2 p1
- p2.firstName "Martha"
- p2.age 30
- p1 and p2 now refer to the same object, and both
now refer to information about Martha! - To create an actual new object, you must use the
new operator with a constructor function
31More about objects
- Objects behave differently from primitive values
when used as function arguments - if an argument is an object, a function can
modify its properties - function nextYear(p)
- p.age
- This code will actually increment person's age in
the object - Deleting Objects
- An object can be deleted by setting any variables
that reference it to null - To delete specific properties of an object or
elements of an array, you can use the delete
operator
32Properties as objects
- A property of an object can itself be an object
- The built-in document object contains a large
number of properties pertaining to contents of a
web page - Many of these properties are arrays or objects.
If your web page contains a form named info, you
could refer to it in a script as
document.forms.info - Hence, a property of an object can be either a
primitive value or another object, and the
objects can be nested to an arbitrary depth
33Properties as objects
- Constructor definition
- function job(what, who, yr, mo, dy)
- this.title what
- this.person who
- this.startDate new Date(yr, mo, dy)
- Object creation
- var Joe new person("Joe", "Zeelane", 46)
- project1 new job("Report", Joe, 97, 06, 13)
- Resulting object properties
- project1.person, project1.startDate
- And primitive values properties
- project1.person.firstName
34Adding properties to objects
- One can add properties to existing objects by
using the special prototype property - available for all objects that are created with
the new operator, including built-in object types
as well as any constructors defined by programmer - person.prototype.gender ""
- This statement adds a new property called gender
to the person object - All instances of this new property will be set to
the specified value - The gender property will be added to person
objects that have already been constructed, as
well as to any that are created later
35Methods
- JavaScript methods are functions that are
associated with an object. Examples - a.reverse()
- reverses the order of the elements of an array
- string s a.join(")
- forms a string by combining an array's elements,
separated by vertical bars - Methods are always listed at the end of object
definition, and followed by (possibly empty) list
of arguments in parentheses
36Creating a method
- function personText()
- var s
- this.firstName" this.lastName
"("this.age")" - return s
- To make this function a method of person, add a
line to your constructor function to assign it - function person(first, last, yrs)
- this.firstName first
- this.lastName last
- this.age yrs
- this.formatted personText
- And use it as follows
- document.write(Joe.formatted())
37Universal Methods
- There are three methods that are available for
all objects - eval evaluates a string as JavaScript code in the
context of the calling object, and returns its
value - toString returns a string representing a numeric
value in a specified radix - valueOf returns the primitive value of an object
- Two other methods are available for large numbers
of objects - constructor() is available for all objects
created by constructor functions. It returns the
function that created an object - handleEvent() is available for all objects that
have event handlers. It calls an event handler
for a specific event
38JavaScript Entities
- One can parameterize HTML using
document.write(ln) commands such as - document.writeln(string1 Jsvariable
string2) - There is another way of achieving this without a
ltSCRIPTgt tag and no document.writeln -- namely - ltIMG widthJSvar1 srcJSvar2 gt
- where JSvar1 and JSvar2 are JavaScript variables
holding width and URL of image - Syntax is modeled on that for special characters
where - GT is gt etc.
- Such JavaScript Entities can only appear on right
hand side of attributes values and cannot appear
in HTML text such as titles - document.writeln approach has no such
restriction!
39Javascript vs. windows
- Every script runs in a window
- The window object is the "outermost" object in
the JavaScript hierarchy - All variables and functions declared in scripts
are actually properties and methods of the window - a variable x is actually window.x
- The symbol self is equivalent to window
- Each window object corresponds to one browser
window on the host computer's screen - It is possible to communicate between windows be
referring to or setting other windows variables
40Inter-window communication
- To open additional windows
- var win2 open("someFile.htm", "newWin",
features) - This opens a new browser window, and returns a
new window object in the variable win2 - The new window can now be accessed
- win2.document.write(someText) win2.toolbar.visibl
e false win2.document.close() - Scripts in win2 can access the original window
- opener.win2status "ready
- Or re-write original window contents
- opener.location newtext.html
-
41Javascript vs. documents
- Every window has a document property which
manages all text, graphics, and other data
displayed in the window - A document object has properties that reflect the
HTML elements in the window, like the arrays - document.links
- document.images
- document.applets
- document.embeds
- document.forms
42The Image Object
- The JavaScript Image object allows scripts to
perform some basic operations on images stored in
file - Image objects are created automatically when
browser encounters ltIMGgt tags in a document - Scripts can create Image objects and assign them
to variables with the new Image() constructor - These objects are not displayed on the screen,
but they can be loaded with images from files and
later copied to other images that are in the
document - Allows you to change an image quickly in response
to user actions - You can create simple animation by rapidly
sequencing through a series of images
43Input/Output
- JavaScript provides several types of dialog boxes
that can be used with a single statement - These dialogs are all available through methods
of the window object - alert(mes) creates an alert box that displays the
specified string - confirm(mes) creates a confirm box that displays
the specified string and two buttons - Returns true if the user clicks OK, or false if
the user clicks Cancel - prompt(mes, default) creates a dialog box
displaying string message, a text box and two
buttons - The default string is initially displayed in text
box the user may enter other text - If the user clicks OK, prompt returns a string
containing the contents of the text box. If the
user clicks Cancel, prompt returns null
44Forms
- HTML forms are a very powerful way to interact
with the user of a web page - Originally intended for sending information to
servers, but use of JavaScript allows browser to
manipulate forms locally in browser - Browser creates Form objects corresponding to all
HTML ltFORMgt tags and stores them as elements of
the document.forms array - If the ltFORMgt tag has a NAME attribute, the Form
object can be referenced by its name as a
property of document - ltFORM NAME"userData"gt can be referenced as
document.userData
45Forms 2
- A form contains interactive elements such as
buttons and text boxes - Browser creates objects for each type of form
element and stores them in elements array - They can be referenced as elements0,
elements1, and so forth - If the elements' HTML tags have NAME attributes,
the objects can be referenced by their names as
properties of the form
46Forms 3
- ltFORM NAME"userData ACTIONprocessForm.cgigt
- First nameltINPUT TYPE"text NAME"first"gt ltBRgt
- Last nameltINPUT TYPE"text" NAME"last"gt ltBRgt
- Address ltTEXTAREA NAME"addr" ROWS"4"
COLS"32"gtlt/TEXTAREAgt ltPgt - ltINPUT TYPE"button" NAME"btn" VALUE"Accept
data" ONCLICK"processData(this.form)"gt - ltINPUT TYPE"reset" NAME"rst" VALUE"Start
over"gt - ltINPUT TYPEhidden NAMEfngt lt/FORMgt
- The first text box could be referenced by any of
this - document.userData.first
- document.userData.elements0
- document.forms0.first
- document.forms0.elements0
47Forms vs. JavaScript
- Form objects and all their properties and
elements can be referenced by any statements in a
script - Some properties are read-only, but many can be
modified - Options can be added to or removed from a select
box - additional Option objects can be created with the
new Option() constructor
48Event handlers in forms
- processData has been defined as onclick event
handler for one of the buttons - processData() can manipulate the Form object and
its elements - function processData (fo)
- fullName fo.first.value" "fo.last.value
- fo.fn.value fullName fo.submit()
-
- Before the form is submitted to server, the
function calculates full name and passes it on
along with values of other elements
49Types of events
- onsubmit onreset
- onchange onclick ondblclick
- onkeydown onkeypress onkeyup
- onmousedown onmousemove onmouseout onmouseover
onmouseup - onabort onerror onload onunload
- onmove onresize onblur onfocus ondragdrop
- etc.
50The event object
- JavaScript can pass an event object to event
handlers - event object contains a number of properties that
provide detailed information about the event,
such as type of even, mouse button pressed, event
coordinates, window size after event, etc - document.links2.onclick reportEvent.
- function reportEvent(ev)
- alert("Event of type " ev.type
- " occurred at X" ev.pageX
- ", Y" ev.pageY)
-
51HTML Reflection
- JavaScript built-in variables are initialized as
the web page is loaded - Many of these variables are copies, or
reflections, of the attribute values of various
HTML tags - Example document.bgColor is a reflection of the
bgcolor attribute of the ltBODYgt tag. - These built-in variables reflect much of the
content of the web page, allowing scripts to read
and, in some cases, modify this information - A script can change the web page background color
with a statement like - document.bgColor "red"
52HTML Reflection
- A more powerful example is
- document.tags.H1.color "blue"
- This changes the color of all ltH1gt headings on
the web page - This looks a little like what style sheets can do
is it the same thing? - No. It could be used as a stylesheet, but, in
addition to this, the statement above can be
executed at runtime to dynamically change all H1
headers to red.
53HTML Reflection
- ltFORMgt
- Enter a number
- ltINPUT TYPE"text" NAME"num1" gt ltPgt
- Enter another number
- ltINPUT TYPE"text" NAME"num2" gt ltPgt
- ltINPUT type"button" value"Add the numbers"
onclick"addFields(this.form)"gt ltPgt - The sum is ltINPUT TYPE"text" NAME"result"
gt - lt/FORMgt
- This is actually handled by
- function addFields(form)
- var sumeval(form.num1.value)
eval(form.num2.value) - form.result.value sum
-
-
54Form example (again..)
- This example is actually highly non-trivial!
- this refers to the object being reflected, i.e,
the button! - form is property of every element of the form
that returns the Form object (note uppercase) - Form is an external object reflecting an HTML
form in a document - Hence, this.form can be passed to a function
which, in turn, can access all properties and
methods of the HTML form form which the function
was called
55Some examples.
56Hello World Example
- ltHTMLgt
- ltHEADgtltTITLEgtAn Examplelt/TITLEgtlt/HEADgt
- ltBODYgt
- lt!-- Insert HTML here --gt
- ltSCRIPT LANGUAGE"JavaScript"gt
- document.writeln("ltH1gtHello World!lt/H1gt")
- lt/SCRIPTgt
- lt!-- Insert more HTML here --gt
- lt/BODYgt
- lt/HTMLgt
57Hello World Example (contd)
- There is only one JavaScript statementdocument.w
riteln("ltH1gtHello World!lt/H1gt") - The writeln method writes its argument into the
current document - The script is in the ltBODYgt since it writes HTML
code into the document other scripts are written
in the ltHEADgt so they are processed and available
in body - In advanced applications, when JavaScript object
is actually defined becomes tricky and is an
example of how there are intrinsically undefined
features in the language - Scripts may be hidden from old browsers using
ugly constructltSCRIPT LANGUAGEJavaScript
gtlt!-- A comment to a dinosaur-- gt Bunch of
Exciting JavaScript Statements ..//script ends
here --gtlt/SCRIPTgt
58Form Example
- ltHTMLgt
- ltHEADgtltTITLEgtJavaScript with Formslt/TITLEgt
- ltSCRIPT LANGUAGE"JavaScript"gt
- function compute()
- if ( window.confirm("Is this what you want?") )
- aForm.result.value eval(aForm.expr.value)
-
- lt/SCRIPTgtlt/HEADgt
- ltBODYgtltFORM NAME"aForm"gt Enter expression
- ltINPUT TYPE"text" NAME"expr" SIZE15gt
- ltINPUT TYPE"button" VALUE"Compute!"
- onClick"compute()"gt ltBRgt Result
- ltINPUT TYPE"text" NAME"result" SIZE15gt
- lt/FORMgtlt/BODYgt
- lt/HTMLgt
59Form Example (contd)
- confirm is a method of the Window object which
pops up a window requesting confirmation of
requested action - eval is a built-in JavaScript function
- onClick is a JavaScript event handler and onClick
your stuff executes JavaScript code yourstuff - Note the user-defined names (aForm, expr, result)
referred to in the script
60Example of Parameterized HTML
- ltHTMLgtltHEADgtltTITLEgtJavaScript Used to
Parameterize HTMLlt/HTMLgt - ltSCRIPT LANGUAGEJavaScript gtvar
imagewidth600// These could be changed by form
var imagefilemy.gif //input or some
computation // based on size of window
(available to JavaScript)lt/SCRIPTgtlt/HEADgt - ltBODYgtlth2gtPlain old HTML of any typelt/h2gt
ltSCRIPT LANGUAGEJavaScript
gtdocument.writeln(ltimage aligntop width
imagewidth src imagefile
gt)lt/SCRIPTgt - ltbgtAnd the beat goes on lt/bgt
- lt/BODYgtlt/HTMLgt
- Note the horrible mix of JavaScript and HTML).
JavaScript Variables
61Measuring link speed - HTML
- lthtmlgt ltheadgt
- ltscript srcbandwidth.js language"JavaScript1.2
"gt - alert (script not found)
- lt/scriptgt
- ltscript language"JavaScript1.2"gt
- initTimer()
- testimage new Image(480,360)
- testimage.onloadtimeIt
- testimage.src "htmlImages/linktest.gif"
- lt/scriptgtlt/headgt
- ltbodygt
- ltimg src"htmlImages/linktest.gif"gt
- lt/bodygtlt/htmlgt
62Measuring link speed - script
- var size 66826.0 var eTime 0 var startTime
0 - function print(s)
- alert ("bandwidth.js "s)
- function timeIt()
- time new Date()
- eTime time.getTime() - startTime 1
- var bwth estimateBandwidth()
- commentBandwidth(bwth)
- function initTimer()
- time new Date()
- startTime time.getTime()
- function estimateBandwidth()
- var bwthparseInt(8.0size/eTime)
- return bwth
- function commentBandwidth(b)
- print("Your effective link speed is "b"
Kbps")