Javascript DBI – Representation and Management of Data on the Internet.
-
date post
21-Dec-2015 -
Category
Documents
-
view
212 -
download
0
Transcript of Javascript DBI – Representation and Management of Data on the Internet.
Overview
• A "scripting" language for HTML pages• Embed code in HTML pages so they are
downloaded directly to browser• The browser interprets and executes the script (it
is not compiled)• Do not declare data types for variables (loose
typing)• Dynamic binding – object references checked at
runtime
Overview (cont.)
• Scripts can manipulate "browser objects:"– HTML form elements– Images– Frames– etc.
• For security – cannot write to disk (when run on a client)
It is not Java
• Java :– compilation required– can create “stand alone” application– much more complex
• more commands
• more built-in functions
• object-oriented
Web browser
HTML Page:
<SCRIPT>
…code..…
</SCRIPT>
Desktop access
InternetHTML/HTTP
TCP/IP
HTML/HTTP
TCP/IP
Web
(HTTP)
Server
HTML
pages w/
embedded
script
Remote host
built-in
JavaScript
interpreter
Web Architecture for JavaScript"CLIENT" "SERVER"
Example<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>An Hello World Example</TITLE><SCRIPT LANGUAGE = "JavaScript">document.writeln("<H1>Can't you find a better example than Hello World?</H1>);</SCRIPT></HEAD>
<BODY> <!-- An empty document body --> </BODY></HTML>
Past and Present
• Built into Netscape Navigator since v2.0 (early 1996)
• Developed independently of Java• Proprietary, but submitted as standard and built
into Microsoft IE 3.0 and later• Standardized by ECMA (European Computer
Manufacture’s Association) into ECMAscript• EMCAscript joins JavaScript and Jscript to one
standard
Client and Server
• JavaScript can be used – On the client side– On the server
• More reliable on client than Java right now
• Useful for developing interactive interface
• Also useful for "gluing" Java applets together
CGI and other Server-side Architectures
• Strengths– allows access to server
files and databases
– makes no assumptions about client computer capabilities, puts little burden on it
– easier to manage and control on server
– more secure for client
• Weaknesses– puts most of processing
load on server– requires round-trip for
every submission, using valuable bandwidth
– cannot provide instantaneous response expected with GUI
– less secure for server
JavaScript Reserved Keywords
• break• case• continue• delete• do• else • false• for
• function• if• in• new• null• return• switch• this
• true• typeof• var• void• while• with
Non Used Reserved Words
• catch• class• const• debugger• default• enum• export
• extends• finally• import• super• try
Javascript Variables
• Untyped!
• Can be declared with var keyword:var foo;
• Can be created automatically by assigning a value:foo=1; blah="Hi Rakefet";
Variables Names
• A variable name can be any valid identifier• The identifier is a series of characters
– Consisting of letters, digits, underscores (_) and dollar signs ($)
– Does not begin with a digit– Does not contain any space
• JavaScript is case sensitive
Variables
• Using var to declare a variable results in a local variable (inside a function)
• If you do not use var – the variable is a global variable
Literals
• The typical bunch:– Numbers 17 123.45– Strings “Let it be”– Boolean: true false– Arrays: [1,“ab ba”,17.234]
Arrays can hold anything!
Operators
• Arithmetic, comparison, assignment, bit wise, Boolean (pretty much just like Java)
+ - * / % ++ --
== != > < >= <=
&& || ! & | << >>
+= -= *= /= %=
Conditional Operators
• equalsif (a == b) {…}
• not equalsif (a != b) {…}
• greater than or equal toif (a >= b) {...}
• less than or equal toif (a <= b) {...}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>Using Variables</TITLE><SCRIPT LANGUAGE = "JavaScript">
var firstNumber = 11, secondNumber = 23, sum;sum = firstNumber + secondNumber;document.write("<FONT COLOR = 'blue' SIZE = '6'>The sum of " + firstNumber + " and " + secondNumber + " is </FONT>");document.write(" <FONT COLOR = 'magenta' SIZE = '7'>" + sum + "</FONT>");
</SCRIPT></HEAD><BODY> <!-- An empty document body --> </BODY></HTML>
Control Structures
• Some just like Java:if if-else ?: switch
for while do-while
• And a few not like in Javafor (var in object)
with (object)
JavaScript Constructs
• sequence (block)– executes with no conditions– semicolons optional using one statement per line,
but not a bad thing to use all the time
var metushelahAge = 130; var yourAverageAgeyourAverageAge = metushelahAge - 98var myObject = new Object("initial value")more statements here..…..…..
JavaScript Constructs
• condition (selection)if (condition) {statements if true}else {statements if false}
if (metushelahAge < yourAverageAge) { document.write ("<body><h2>its true that
Metushelah is younger than most of you,") document.write ("<br>computers never lie!</h2>
</body>")}
JavaScript Constructs• loop (iteration)
– both for and while loops are available, e.g.while (init expression; condition; update expression){statements}
for (var i=0; i < inputAge.length; i++) {var oneChar = inputAge.substring (i, i+1)if (oneChar < "0" || oneChar > "9") {
alert("Please enter a valid number “+ oneChar + " is not valid.")
}}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>Loops Example</TITLE><SCRIPT LANGUAGE = "JavaScript">
for (var counter = 1 ; counter <= 7 ; ++counter) { document.write(“<P><FONT COLOR = 'magenta' SIZE = ‘ “ + counter + “ '> Now with font size " + counter + " </FONT></P> “);
}</SCRIPT></HEAD>
<BODY> <!-- An empty document body --> </BODY></HTML>
Javascript Functions
• The keyword function used to define a function (subroutine):
function add(x,y) {
return(x+y);
}
Function Input and Outout
• Numbers and Boolean values always passed to functions using call-by-value
• For objects, a call-by-reference is used to pass them to the functions
• Numbers and Boolean values are always returned by value
• Objects returned by reference
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>Functions Example</TITLE><SCRIPT LANGUAGE = "JavaScript">function fibonacciValue() { var value = parseInt(document.fibonacciForm.number.value ); window.status = "Calculating Fibonacci number for " + value; document.fibonacciForm.result.value = fibonacci(value); window.status = "Done Calculating Fibonacci number";}
function fibonacci( n ) { if (n == 0 || n == 1) // base case return n; else return fibonacci( n - 1 ) + fibonacci( n - 2 );}</SCRIPT></HEAD>
<BODY>
<FORM NAME = "fibonacciForm">
<TABLE BORDER = "1" BGCOLOR = "blue">
<TR><TD BGCOLOR = "cyan">Enter a number</TD>
<TD><INPUT NAME = "number" TYPE = "text"></TD>
<TD><INPUT TYPE = "button" VALUE = "Calculate"
ONCLICK = "fibonacciValue()"</TR>
<TR><TD BGCOLOR = "cyan">Fibonacci Value</TD>
<TD><INPUT NAME = "result" TYPE = "text"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>
Global Functions (1)
• escape – changes characters in a string that are not in the ASCII characters set to HEX
• unescape – decodes the escape encoding
• eval – gets a string of JavaScript code, evaluates it and executes it– It allows dynamic code execution
Global Functions (2)
• isNaN – takes a numeric argument and returns true if the value is not a number
• parseFloat – takes a string argument and converts its beginning to a float number (or return NaN)
• parseInt – takes a string argument and converts its beginning to an integer number (or return NaN)
Global Functions (3)
• isFinite – given a numeric argument it returns true if the argument is not– NaN– Number.POSITIVE_INFINITY– Number.NEGATIVE_INFINITY
Objects
• Objects have attributes and methods
• Many pre-defined objects and object types
• Using objects follows the syntax of C++/Java:objectname.attributename
objectname.methodname()
Array Objects
• Arrays are supported as objects
• Attribute length
• Methods include:concat join pop push reverse sort
Creating a New Array
• var a = [“red”, “blue”, “green”, “yellow”]– Allocates an array of 4 cells and initializes the
values
• var b = new Array(5)– Allocates an array of 5 cells without initializing
values
• var c = new Array()– Creates a new empty array
Passing Arrays to Functions
• Arrays can be passed to functions as arguments
• The array is passed by call-by-reference
• The name of the array is given to the function
<HTML><HEAD><TITLE>Arrays Example</TITLE><SCRIPT LANGUAGE = "JavaScript">function start() { var colors = ["red", "blue", "green"] printArray(colors); printArray(colors); }
function printArray( colorsArray ) { // prints the array but also modifies it for (var i in colorsArray) {
var c = colorsArray[i];document.writeln("<FONT SIZE = 5 COLOR =" + c + "> " + c + " </FONT><BR>");colorsArray[i] = "gray";
}}</SCRIPT></HEAD><BODY ONLOAD = "start()"> </BODY></HTML>
Multidimentional Arrays
• var matrix = [ [0, 1, 1], [1, 1, 0], [0, 0, 0]];
• var myArray = [[1, 2, 3], [1], [1, 2]];
• Going over the array
for (var i in myArray ) {
for (var j in myArray[i])
document.write(myArray[i][j]);
Other Object Types
• String: manipulation methods• Math: trig, log, random numbers• Date: date conversions• RegExp: regular expressions• Number: limits, conversion to string
Math Common Methods
• abs(x)• round(x)• ceil(x)• floor(x)• max(x, y)• min(x, y)
• cos(x)• sin(x)• tan(x)• exp(x)• pow(x, y)• sqrt(x)• log(x)
Math Also includes constants
such as: Math.E, Math.PI
String Common Methods (1)
• charAt (index)• charCodeAt(index)• Concat(string)• fromCharCode(value1
, value2, …)• indexOf(substring,
index)• lastIndexOf(substring,
index)
• slice(start, end)• split(string)• substr(start, length)• substring(start, end)• toLowerCase()• toUpperCase()• toString()• valueOf()
Methods that Generate HTML• anchor(name) – wraps the source with
– <A name = name></A>• big() – wraps the source with
– <BIG></BIG>• blink() – wraps with
– <BLINK></BLINK>• bold() – wraps the source with
– <B></B>• fixed() – wraps the source with
– <TT></TT>
More Methods that Generate HTML
• fontcolor(color) – wraps with – <FONT color=“color”></FONT>
• fontsize(size) – wraps with – <FONT size=“size”></FONT>
• italic() – wraps with – <I></I>
• link(url)– <A href = url></A>
More Methods that Generate HTML
• small() – wraps the source with– <SMALL></SMALL>
• strike() – wraps the source with – <STRIKE></STRIKE>
• sub() – wraps the source with– <SUB></SUB>
• sup() – wraps the source with – <SUP></SUP>
Date Common Methods
• getDate(), getFullYear(), getMonth(), getDay
• getTime(), getHours(), getMinutes(), getSeconds(), getMilliseconds()
• All these have a version with UTC (e.g., getUTCDate()) for GMT (Greenwich Mean Time)
<HTML>
<HEAD><TITLE>Arrays Example</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function getTimes() {
var current = new Date();
var out = new String();
out = "Day: " + current.getDay()+"\n";
out = out.concat("Month: " + current.getMonth() + "\n");
out = out.concat("Year: " + current.getFullYear() + "\n");
out = out.concat("GMT Time: " + current.toUTCString() + "\n");
out = out.concat("Time: " + current.toString() + "\n");
timesForm.output.value = out;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="timesForm">
<P>
<INPUT NAME = "getTimeButton" TYPE = "button" VALUE = "Get Time“ ONCLICK = "getTimes()">
<P>
<TEXTAREA NAME = "output" ROWS ="10“ COLS="42">
</TEXTAREA>
</FORM>
</BODY>
</HTML>
Predefined Objects
• In JavaScript the following objects are automatically created for you (always available)– document– navigator– screen– window
The document Object
• Many attributes of the current document are available via the document object:
Title Referrer
URL Images
Forms Links
Colors
document write method
• document.write() like a print statement – the output goes into the HTML document
document.write("My title is" + document.title);
string concatenation
Objects Hierarchy
• JavaScript objects include object hierarchy + (property or method)– window.document.lastModified– metushelahBirthday.getYear()
• need not be fully qualified– document.lastModified
• proceeds from most to least general– window.document.forms[0].inputText1.value
• all names are case sensitive
Objects Object Oriented
• Objects – complex data types or “containers” that have both data and code
• Methods – code or “functions” that work on an object’s properties
• Properties – data that are stored and retrieved via object references
• This is not true "OO" because the object hierarchy is not extensible, you can create new objects, but cannot extend existing ones
The with Statement
• Establishes the default object for a set of statements
• Within the set of statements, any property references that do not specify an object are assumed to be for the default object
Example of with
var a, x, y
var r=10
with (Math) { a = PI * r * r x = r * cos(PI) y = r * sin(PI/2)
}
What is Dynamic HTML
• Dynamic HTML (DHTML) is an all-in-one word for web pages that use – Hypertext Markup Language (HTML),
– Cascading Style Sheets (CSS), and
– rely on JavaScript to make the web pages interactive
• DHTML describes the abstract concept of – breaking up a page into manipulable elements
– exposing those elements to a scriping language
– the script perform the manipulations
Why Do We Need DHTML?
• HTML in its traditional form is not powerful enough to create the interactive and multimedia-rich documents
• Without DHTML, the browser must download another page from the server to change what the user sees on the screen
JavaScript (+)
• What JavaScript can do: – Control document appearance and content– Control the behavior of the browser– Interact with document content– Interact with the user– Read and write client state with cookies– Interact with applets– Manipulate embedded images
JavaScript(-)
• What JavaScript cannot do: – No graphics capabilities– No reading/writing of files on the client side– No networking except to arbitrary URLs– No multithreading
Dynamic HTML Object Model
• Gives access to all the elements on the Web page:– Frames
– Applets
– Images
– Forms
– StyleSheets
– etc.
• Scripts are used to dynamically change objects and thus the Web page
Document Object Model (D.O.M)
• When an HTML page loads into a scriptable browser, the browser creates a hidden, internal roadmap of all the elements it recognizes as scriptable objects
• The roadmap is hierarchical• The scriptable objects are “document objects”• Document objects in a page can be addressed and moved
around, font sizes and styles can change as the cursor travels over them … – all this is controlled by scripting
• Unfortunately, Netscape and Microsoft have somewhat incompatible implementations of DHTML
The Object Model
• Naming hierarchy used to access individual elements of a HTML document
• Easy to use if you name all entities:– Forms, fields, images, etc.
DOM Example<FORM NAME=myform ACTION=…Please Enter Your Age:<INPUT TYPE=TEXT NAME=age><BR>And your weight:<INPUT TYPE=TEXT NAME=weight><BR></FORM>
<FORM NAME=myform ACTION=…Please Enter Your Age:<INPUT TYPE=TEXT NAME=age><BR>And your weight:<INPUT TYPE=TEXT NAME=weight><BR></FORM>
• From JavaScript you can get the age input field as: • document.myform.age.value
Collections all and children
• all is used to refer to all the descendents of an object
• children is used to access only direct children
for(var loop=0; loop<document.all.length; ++loop)
elements += “<BR>”+document.all[loop].tagName;
Only in In Microsoft
Internet Explorer
Netscape vs. IE
• These features are specific to Netscape Navigator 4.0, and aren't supported by Microsoft: – <layer> tag– JavaScript Style Sheets– Bitstream fonts
IE vs. Netscape
• These features are specific to Microsoft Internet Explorer 4.0, and aren't supported by Netscape: – Direct Animation Controls– data binding– VBScript– OpenType fonts
The Solutions
• Use JavaScript to detect the browser– <SCRIPT LANGUAGE="JavaScript">– <!--– ns4 = (document.layers)? true:false– ie4 = (document.all)? true:false– function init() {– if (ns4) block = document.blockDiv– if (ie4) block = blockDiv.style– }– //-->– </SCRIPT>
• The document.layers object is specific to Netscape 4.0, while the document.all object is specific to IE 4.0.
Some Important Objects• window:
– the top-level object – the window object is the "parent" object for all other objects in Navigator
– has properties that apply to the entire window – there is also a window object for each "child window" in a
frames document
• document: – contains properties based on the content of the document, such as
title, background color, links, and forms
• location: – has properties based on the current URL
• history: – contains properties representing URLs the client has previously
requested
window
plugins
document
document
document
frames
history
navigator
location
event
screen
all
collections
anchors
applets
body
embeds
images
forms
filters
links
plugins
styleSheets
scripts
objects In IE
Information about the Browser
• The Window object contains references to three objects that contain information about the browser or the browser window itself:– the Navigator object – the Location object – the History object
<script>
for (prop in navigator) {
document.write(prop + " -> " + navigator[prop], "<br>");
}
document.write("<h3>Plugins</h3>");
for (i=0; i<navigator.plugins.length; i++) {
document.write(navigator.plugins[i].name, "<br>");
}
document.write("<h3>Mime Types</h3>");
for (i=0; i<navigator.mimeTypes.length; i++) {
document.write(navigator.mimeTypes[i].type, "<br>");
}
</script>
More System Info
function _get_version(){
return Math.round(parseFloat(navigator.appVersion) * 1000);}
function _get_os(){ if (navigator.appVersion.indexOf("Win95") > 0) return "WIN95"; else if (navigator.appVersion.indexOf("Win16") > 0) return "WIN31"; else if (navigator.appVersion.indexOf("Mac") > 0) return "MAC"; else if (navigator.appVersion.indexOf("X11") > 0) return "UNIX"; else return "UNKNOWN";}
Sys Info (cont.)
if (navigator.appName.substring(0,8) == "Netscape") {
// if so, set the name variable appropriately
browser.name = "NN";
// then parse navigator.appVersion to figure out what
// version
browser.version = _get_version();
// Then use appVersion again to determine the OS
browser.os = _get_os();
}
Sys Info (cont.)
else if (navigator.appName.substring(0,9) == "Microsoft") { browser.name = "MSIE"; browser.version = _get_version(); browser.os = "WIN95";}else { browser.name = navigator.appName; browser.version = _get_version(); browser.os = _get_os();}
Sys Info (cont.)
with (browser) {
document.write("<p>Name=", name);
document.write("<p>Version=", version);
document.write("<p>OS=", os);
}
<HTML>
<HEAD><TITLE>Arrays Example</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function start() {
window.alert( paragraphText.innerText );
paragraphText.style.color = 'red';
paragraphText.innerText = "Virus has been installed !!"
}
</SCRIPT>
</HEAD>
<BODY ONLOAD = "start()">
<FONT SIZE = '5'>
<P ID = "paragraphText">
A new virus is now being install in your computer.</P></FONT>
</BODY>
</HTML>
An Example
JavaScript Object Hierarchy
Window
Document
Form
parent
top
self
frames
link
anchorbutton
radio
checkbox
select
etc.
The window
• Next, we will examine what can be done with a window
• We follow Netscape properties and methods
Window Properties (1)
• closed Specifies whether a window has been closed • defaultStatus Reflects the default message
displayed in the window's status bar • document Contains information on the current
document, and provides methods for displaying HTML output to the user
• frames An array reflecting all the frames in a window
• history Contains information on the URLs that the client has visited within a window
Windows Properties (2)
• innerHeight Specifies the vertical dimension, in pixels, of the window's content area
• innerWidth Specifies the horizontal dimension, in pixels, of the window's content area
• length The number of frames in the window
• location Contains information on the current URL
• locationbar Represents the browser window's location bar
Windows Properties (3)
• menubar Represents the browser window's menu bar
• name A unique name used to refer to this window • opener Specifies the window name of the calling
document when a window is opened using the open method
• outerHeight Specifies the vertical dimension, in pixels, of the window's outside boundary
• outerWidth Specifies the horizontal dimension, in pixels, of the window's outside boundary.
Windows Properties (4)
• pageXOffset Provides the current x-position, in pixels, of a window's viewed page
• pageYOffset Provides the current y-position, in pixels, of a window's viewed page
• parent A synonym for a window or frame whose frameset contains the current frame
• personalbar Represents the browser window's personal bar (also called the directories bar)
Window Properties (5)
• scrollbars Represents the browser window's scroll bars
• self A synonym for the current window• status Specifies a priority or transient message in the
window's status bar• statusbar Represents the browser window's status
bar• toolbar Represents the browser window's tool bar • top A synonym for the topmost browser window • window A synonym for the current window
Window Methods (1)
• alert Displays an Alert dialog box with a message and an OK button
• back Undoes the last history step in any frame within the top-level window
• blur Removes focus from the specified object • captureEvents Sets the window or document to
capture all events of the specified type • clearInterval Cancels a timeout that was set
with the setInterval method
Window Methods (2)
• clearInterval Cancels a timeout that was set with the setInterval method
• clearTimeout Cancels a timeout that was set with the setTimeout method
• close Closes the specified window • confirm Displays a Confirm dialog box with the
specified message and OK and Cancel buttons • disableExternalCapture Disables external
event capturing set by the enableExternalCapture method
Window Methods (3)
• enableExternalCapture Allows a window with frames to capture events in pages loaded from different locations (servers)
• find Finds the specified text string in the contents of the specified window
• focus Gives focus to the specified object • forward Loads the next URL in the history list • handleEvent Invokes the handler for the
specified event
Window Methods (3)
• home Points the browser to the URL specified in preferences as the user's home page
• moveBy Moves the window by the specified amounts
• moveTo Moves the top-left corner of the window to the specified screen coordinates
• open Opens a new web browser window
• print Prints the contents of the window or frame
Window Methods (4)
• prompt Displays a Prompt dialog box with a message and an input field
• releaseEvents Sets the window to release captured events of the specified type, sending the event to objects further along the event hierarchy
• resizeBy Resizes an entire window by moving the window's bottom-right corner by the specified amount
• resizeTo Resizes an entire window to the specified outer height and width
Window Methods (5)
• routeEvent Passes a captured event along the normal event hierarchy
• scroll Scrolls a window to a specified coordinate
• scrollBy Scrolls the viewing area of a window by the specified amount
• scrollTo Scrolls the viewing area of the window to the specified coordinates, such that the specified point becomes the top-left corner
Window Methods (6)
• setInterval Evaluates an expression or calls a function every time a specified number of milliseconds elapses
• setTimeout Evaluates an expression or calls a function once after a specified number of milliseconds has elapsed
• stop Stops the current download
The document
• Next, we will examine what can be done with a document
• We follow Netscape properties and methods
Properties of document
• alinkColor A string that specifies the ALINK attribute
• anchors An array containing an entry for each anchor in the document
• applets An array containing an entry for each applet in the document
• bgColor A string that specifies the BGCOLOR attribute
• cookie Specifies a cookie
Document properties (2)
• domain Specifies the domain name of the server that served a document
• embeds An array containing an entry for each plug-in in the document
• fgColor A string that specifies the TEXT attribute
• formName A separate property for each named form in the document
Document properties (3)
• forms An array a containing an entry for each form in the document
• images An array containing an entry for each image in the document
• lastModified A string that specifies the date the document was last modified
• layers Array containing an entry for each layer within the document
• linkColor (vlinkColor) A string that specifies the LINK (VLINK) attribute
Document properties (4)
• links An array containing an entry for each link in the document
• plugins An array containing an entry for each plug-in in the document
• referrer A string that specifies the URL of the calling document
• title A string that specifies the contents of the TITLE tag
• URL A string that specifies the complete URL of a document
Document methods (1)
• captureEvents Sets the document to capture all events of the specified type
• close Closes an output stream and forces data to display
• getSelection Returns a string containing the text of the current selection
• handleEvent Invokes the handler for the specified event
• open Opens a stream to collect the output of write or writeln methods
Document methods (2)
• releaseEvents Sets the window or document to release captured events of the specified type, sending the event to objects further along the event hierarchy.
• routeEvent Passes a captured event along the normal event hierarchy
• write Writes one or more HTML expressions to a document in the specified window
• writeln Writes one or more HTML expressions to a document in the specified window and follows them with a newline character
<HTML><HEAD><SCRIPT LANGUAGE="JavaScript1.1">// open a new windowvar n = window.open('', 'f',
'left=100,top=150,width=400,height=400');// dynamically create frames in that new window.// Note the use of about:blank URL to get empty framesn.document.write('<frameset rows="50%,50%"
cols="50%,50%">');n.document.write('<frame name="f1" src="about:blank">');n.document.write('<frame name="f2" src="about:blank">');n.document.write('<frame name="f3" src="about:blank">');n.document.write('<frame name="f4" src="about:blank">');n.document.write('</frameset>');
// An array of the colors we cycle through for the animation
colors = new Array("red","green","blue","yellow","white");
// An array of the frames we cycle through (in this order)
windows = new Array(n.f1, n.f2, n.f4, n.f3);
// The current color and frame counters
var c = 0, f = 0;
// A variable that holds the current timeout id (used to cancel the timeout)
var timeout = null;
function change_one_frame(){ // dynamically output the HTML necessary to set the
background color windows[f].document.write('<BODY BGCOLOR="' +
colors[c] + '">'); windows[f].document.close(); f = (f + 1) % 4; // increment frame counter c = (c + 1) % 5; // increment color counter // Arrange to be called again in 250 milliseconds // Save the timeout id so that we can stop this crazy thing. timeout = setTimeout("change_one_frame()", 250);}
</SCRIPT></HEAD><!-- start the frame animation when the document is fully loaded
--><BODY onLoad="change_one_frame();"><!-- Create a button to stop the animation with clearTimeout() --><!-- and close the window with close() --><FORM> <INPUT TYPE="button" VALUE="Stop" onClick="if (timeout) clearTimeout(timeout); if (!n.closed)
n.close();"></FORM></BODY></HTML>
Javascript Events
• JavaScript supports an event handling system– You can tell the browser to execute JavaScript
commands when some event occurs– Sometimes the resulting value of the command
determines the browser action
Events on TAGS
• If an event applies to an HTML tag, then you can define an event handler for it
• The name of an event handler is the name of the event, preceded by "on“
• For example, the event handler for the focus event is onFocus
• The general syntax is<TAG eventHandler="JavaScript Code">
Handling Events
• In Navigator 4.0, JavaScript includes event objects as well as event handlers
• Each event has an event object associated with it• The event object provides information about the
event, such as the type of event and the location of the cursor at the time of the event
• When an event occurs, and if an event handler has been written to handle the event, the event object is sent as an argument to the event handler
Handeling the Event
• Next, you need to define a function that handles the event
• The argument evnt is the event object for the event
function clickHandler(evnt) {
//What goes here depends on how you want to handle the event.
}
JavaScript Object Eventswindow, e.g. browser’s viewable area
document, e.g. home.html
text1 text2
text4text3
A B C D
1 2 3 4 5 6 7 8
Submit Button
Form #1, e.g. user-input
changing
the text
triggers
“onChange”
event
clicking
the button
triggers
“onClick”
event
Events Example
<BODY BGCOLOR=WHITE onUnload="restore()"><H5>Hello - I am a very small page!</H5><SCRIPT>savewidth = window.innerWidth;saveheight = window.innerHeight;function restore() { window.innerWidth=savewidth; window.innerHeight=saveheight;}// Change the window size to be smallwindow.innerWidth=300; window.innerHeight=50;document.bgColor='cyan';</SCRIPT>
Immediate Invocation
<html><body>
<h1>Immediate invocation of JavaScript</h1>
<script language="JavaScript">
<!-- begin to hide code if necessary
document.write("<hr><p>This page was updated on " + document.lastModified + ".</p>")
// end hiding code -->
</script>
</body></html>
Deferred Invocation<html><head><script language="JavaScript">function showDate() {
document.write("<hr><p>This page was updated on " + document.lastModified + ".</p>")
} </script></head><body><h1>Deferred invocation of JavaScript</h1><form><input type="button" name="test" value="showDate"
onClick="showDate()"></form></body></html>
<HTML><HEAD><TITLE>Invocation Example</TITLE><SCRIPT LANGUAGE = "JavaScript">
document.writeln("<FONT SIZE = '5' COLOR = 'blue'>Script at the head of the Document</FONT>");
function p1() {
window.confirm("Continue?");document.writeln("<FONT SIZE = '5' COLOR = 'orange'>At function p1</FONT>");
}
function p2() {document.writeln("<FONT SIZE = '5' COLOR = 'orange'>At function p2</FONT>");
}</SCRIPT></HEAD> Invocations Example
<BODY ONLOAD = "p1()"><FONT SIZE = '5'> <P ID = "paragraphText">Some Text in the document body</P></FONT>
<SCRIPT LANGUAGE = "JavaScript">document.writeln("<FONT SIZE = '5' COLOR = 'orange'>At a script in the body</FONT>");
p2();</SCRIPT><P>After the script in the body.
</BODY></HTML>
Immediate Invocation
• In forms handling, unless the form is already populated, immediate does not make any sense
• An immediate invocation will run the JavaScript immediately!
Some More Events
• onCut, onCopy, onKeydown, onKeyPressed
• onDrag, onDrop, onDoubleClick, onMouseDown, onMouseUp, onDragOver, onDragEnter, onDragLeave
• onScroll, onResize, onSelect, onStop, onUnload
Dialog Boxes
• alert(“This is a JavaScript alert”)– user can “escape” to proceed
• confirm(“Are you sure you want to submit this?”)– user must respond yes or no
• var myAge = prompt(“Enter your age”)– user must enter an input string– resulting input is assigned to variable
Buttons
• You can associate buttons with JavaScript events (buttons in HTML forms)
<FORM>
<INPUT TYPE=BUTTON
VALUE="Don't Press Me"
onClick="alert('now you are in trouble!')“ >
</FORM>
<FORM>
<INPUT TYPE=BUTTON
VALUE="Don't Press Me"
onClick="alert('now you are in trouble!')“ >
</FORM>
Some Events (a small sample)
onUnLoad
onLoad
onClick
onMouseUp
onMouseDown
onDblClick
onMouseOver
Window events
Button events
Link events
onBlur v. onClick
• Checks one at a time• Can get tedious • Can get frustrating to
the user• Easier to write
• Checks on click• Bulk checking• Entire validation, all at
once• Harder to write
Form Validation
• You can have JavaScript code that makes sure the user enters valid information
• When the submit button is pressed the script checks the values of all necessary fields:– You can prevent the request from happening
Sample Deferred
Form Validation
<script language="JavaScript">
function validate(form) { var error = "";
if (form.text.value = = "") { error += "Please fill in the text.\n"; }
if (error != "") { alert(error); return (false); } else { return (true);}
</script>
Checking Fields
function checkform() { if (document.myform.age.value == "") { alert("You need to specify an age"); return(false); } else { return(true); }}
function checkform() { if (document.myform.age.value == "") { alert("You need to specify an age"); return(false); } else { return(true); }}
Needs to return true or false!
The Form<FORM METHOD=GET ACTION=foo.cgi
NAME=myform
onSubmit="return(checkform())">
AGE: <INPUT TYPE=TEXT NAME=Age>
<INPUT TYPE=SUBMIT>
</FORM>
Needed to prevent the
browser from submitting!
Important Note about Form Validation!!!
• It's a good idea to make sure the user fills out the form before submitting
• Users can bypass your form – they can create requests manually (or their own forms)
• Your CGI programs cannot rely (solely) on Client-Side JavaScript to validate form fields!
Setting Cookies
Function setCookie(name, value, expires) {
document.cookie = name + “=“ + escape(value) + “; path=/”+
((expires == null) ? “ “ ; expires=“ +
expires.toGMTString());
}
var exp = new Date ();
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 31));
setCookie(“myname”, “myvalue”, exp);
Retrieving Cookiesfunction getCookie(name) {var cname = name + “=“;var dc = document.cookie;if (dc.length > 0) {
begin = dc.indexOf(cname);if (begin != -1) {
begin += cname.length;end = dc.indexOf(“;”, begin);
if (end == -1) end = dc.lengthreturn unescape(dc.substring(begin, end));
}}
return null;}
<HTML><HEAD><TITLE>Moving Objects</TITLE></HEAD><BODY onLoad=“moveIt()><DIV ID="shape1" STYLE="position:absolute; left:100;
top:50; width:300; height:100; clip:rect(0,300,100,0); background-color:red; layer-background-color:red; z-index:2;">
</DIV><DIV ID="shape2" STYLE="position:absolute; left:150;
top:100; width:300; height:100; clip:rect(0,300,100,0); background-color:yellow; layer-background-color:yellow; z-index:1;">
</DIV></BODY></HTML>
function moveIt() {//Get the client window width and height on the initial load. if (firstTime) { if (document.all) { // Internet Explorer maxHeight = document.body.clientHeight-imageHeight maxWidth = document.body.clientWidth-imageWidth } else { // Netscape maxHeight = window.innerHeight-imageHeight maxWidth = window.innerWidth-imageWidth } firstTime = false chgXBy = 1 chgYBy = 1 }
//Get the current position of our image. if (document.all) { // Internet Explorer topPos = document.all.mover.style.pixelTop leftPos = document.all.mover.style.pixelLeft } else { // Netscape topPos = document.mover.top leftPos = document.mover.left }
//If any boundaries have been hit, change direction. //Upper Boundary if (topPos >= maxHeight) { chgYBy = -1 } //Right Boundary if (leftPos >= maxWidth) { chgXBy = -1 } //Lower Boundary if (topPos <= 0) { chgYBy = 1 } //Left Boundary if (leftPos <= 0) { chgXBy = 1 }
//Set the new position of the image. topPos += chgYBy leftPos += chgXBy
if (document.all) { // Internet Explorer document.all.mover.style.pixelTop = topPos document.all.mover.style.pixelLeft = leftPos } else { // Netscape document.mover.top = topPos document.mover.left = leftPos }//Iterate every 20 milliseconds setTimeout("moveIt()",20)}