Javascript DBI Representation and Management of Data on
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 Architecture for Java. Script "CLIENT" "SERVER" Desktop access Remote host Web browser HTML Page: <SCRIPT> …code. . … </SCRIPT> built-in Java. Script interpreter HTML/HTTP TCP/IP Internet HTML/HTTP TCP/IP Web (HTTP) Server HTML pages w/ embedded script
Example <!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN"> <HTML> <HEAD><TITLE>An Hello World Example</TITLE> <SCRIPT LANGUAGE = "Java. Script"> document. writeln("<H 1>Can't you find a better example than Hello World? </H 1>); </SCRIPT> </HEAD> <BODY> <!-- An empty document body --> </BODY> </HTML>
Past and Present • Built into Netscape Navigator since v 2. 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 Java. Script and Jscript to one standard
Client and Server • Java. Script 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
Java. Script 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 • Java. Script 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 • equals if (a == b) {…} • not equals if (a != b) {…} • greater than or equal to if (a >= b) {. . . } • less than or equal to if (a <= b) {. . . }
Boolean Operators • and if (true && true) {…} • or if (true || false) {…} • not if (! false) {. . . }
<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN"> <HTML> <HEAD><TITLE>Using Variables</TITLE> <SCRIPT LANGUAGE = "Java. Script"> var first. Number = 11, second. Number = 23, sum; sum = first. Number + second. Number; document. write("<FONT COLOR = 'blue' SIZE = '6'>The sum of " + first. Number + " and " + second. Number + " 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 Java for (var in object) with (object)
Java. Script’s Basic Constructs • sequence (block( • condition (selection( • loop (iteration(
Java. Script 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 metushelah. Age = 130; var your. Average. Age = metushelah. Age - 98 var my. Object = new Object("initial value") more statements here. . …. .
Java. Script Constructs • condition (selection) if (condition) {statements if true} else {statements if false} if (metushelah. Age < your. Average. Age) { document. write ("<body><h 2>its true that Metushelah is younger than most of you, ") document. write (" computers never lie!</h 2> </body>") }
Java. Script Constructs • loop (iteration) – both for and while loops are available, e. g. while (init expression; condition; update expression){ statements } for (var i=0; i < input. Age. length; i++) { var one. Char = input. Age. substring (i, i+1) if (one. Char < "0" || one. Char > "9") { alert("Please enter a valid number “ + one. Char + " is not valid. ") } }
<!DOCTYPE html PUBLIC "-//W 3 C//DTD HTML 4. 0 Transitional//EN"> <HTML> <HEAD><TITLE>Loops Example</TITLE> <SCRIPT LANGUAGE = "Java. Script"> 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 "-//W 3 C//DTD HTML 4. 0 Transitional//EN"> <HTML> <HEAD><TITLE>Functions Example</TITLE> <SCRIPT LANGUAGE = "Java. Script"> function fibonacci. Value() { var value = parse. Int(document. fibonacci. Form. number. value ); window. status = "Calculating Fibonacci number for " + value; document. fibonacci. Form. 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 = "fibonacci. Form"> <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 = "fibonacci. Value()"</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 Java. Script code, evaluates it and executes it – It allows dynamic code execution
(Global Functions (2 • is. Na. N – takes a numeric argument and returns true if the value is not a number • parse. Float – takes a string argument and converts its beginning to a float number (or return Na. N) • parse. Int – takes a string argument and converts its beginning to an integer number (or return Na. N)
(Global Functions (3 • is. Finite – given a numeric argument it returns true if the argument is not – Na. N – 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
Array Example Code var a = [8, 7, 6, 5]; for (i=0; i<a. length; i++) a[i] += 2; b = a. reverse();
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 = "Java. Script"> function start() { var colors = ["red", "blue", "green"] print. Array(colors); } function print. Array( colors. Array ) { // prints the array but also modifies it for (var i in colors. Array) { var c = colors. Array[i]; document. writeln("<FONT SIZE = 5 COLOR =" + c + "> " + c + " </FONT><BR>"); colors. Array[i] = "gray"; } } </SCRIPT> </HEAD><BODY ONLOAD = "start()"> </BODY> </HTML>
Multidimentional Arrays • var matrix = [ [0, 1, 1], [1, 1, 0], [0, 0, 0]]; • var my. Array = [[1, 2, 3], [1, 2]]; • Going over the array for (var i in my. Array ) { for (var j in my. Array[i]) document. write(my. Array[i][j]);
Other Object Types • String: manipulation methods • Math: trig, log, random numbers • Date: date conversions • Reg. Exp: regular expressions • Number: limits, conversion to string
Math Common Methods • • • abs(x( round(x( ceil(x( floor(x( max(x, y( min(x, y( Math Also includes constants such as: Math. E, Math. PI • • cos(x( sin(x( tan(x( exp(x( pow(x, y( sqrt(x( log(x(
(String Common Methods (1 • • char. At (index) char. Code. At(index) Concat(string) from. Char. Code(value 1, value 2, …) • index. Of(substring, index) • last. Index. Of(substring, index) • • slice(start, end( split(string( substr(start, length( substring(start, end( to. Lower. Case() to. Upper. Case() to. String() value. Of()
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 • get. Date(), get. Full. Year(), get. Month(), get. Day • get. Time(), get. Hours(), get. Minutes(), get. Seconds(), get. Milliseconds() • All these have a version with UTC (e. g. , get. UTCDate()) for GMT (Greenwich Mean Time)
<HTML> <HEAD><TITLE>Arrays Example</TITLE> <SCRIPT LANGUAGE = "Java. Script"> function get. Times() { var current = new Date(); var out = new String(); out = "Day: " + current. get. Day()+"n"; out = out. concat("Month: " + current. get. Month() + "n"); out = out. concat("Year: " + current. get. Full. Year() + "n"); out = out. concat("GMT Time: " + current. to. UTCString() + "n"); out = out. concat("Time: " + current. to. String() + "n"); times. Form. output. value = out; } </SCRIPT> </HEAD>
<BODY> <FORM NAME="times. Form"> <P> <INPUT NAME = "get. Time. Button" TYPE = "button" VALUE = "Get Time“ ONCLICK = "get. Times()"> <P> <TEXTAREA NAME = "output" ROWS ="10“ COLS="42"> </TEXTAREA> </FORM> </BODY> </HTML>
Predefined Objects • In Java. Script 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 URL Forms Colors Referrer Images Links
document write method • document. write() like a print statement – the output goes into the HTML document. write("My title is" + document. title); string concatenation
Objects Hierarchy • Java. Script objects include object hierarchy + (property or method) – window. document. last. Modified – metushelah. Birthday. get. Year() • need not be fully qualified – document. last. Modified • proceeds from most to least general – window. document. forms[0]. input. Text 1. 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 x = r * cos(PI) y = r * sin(PI/2) }
Dynamic HTML CSS Java Script HTML Dynamic HTML
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 Java. Script 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
Java. Script (+) • What Java. Script 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
(-) Java. Script • What Java. Script 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 Style. Sheets 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> • From Java. Script 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 Only in In • children is used to access only direct children Microsoft Internet Explorer an object for(var loop=0; loop<document. all. length; ++loop) elements += “<BR>”+document. all[loop]. tag. Name;
Netscape vs. IE • These features are specific to Netscape Navigator 4. 0, and aren't supported by Microsoft: – <layer> tag – Java. Script 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 – Open. Type fonts
The Solutions • Use Java. Script to detect the browser – – – – – <SCRIPT LANGUAGE="Java. Script"> <!-ns 4 = (document. layers)? true: false ie 4 = (document. all)? true: false function init() { if (ns 4) block = document. block. Div if (ie 4) block = block. Div. 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
all anchors applets window document frames document history navigator location event screen collections objects plugins body embeds filters forms images links plugins scripts style. Sheets In IE
In Netscape
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], " "); } document. write("<h 3>Plugins</h 3>"); for (i=0; i<navigator. plugins. length; i++) { document. write(navigator. plugins[i]. name, " "); } document. write("<h 3>Mime Types</h 3>"); for (i=0; i<navigator. mime. Types. length; i++) { document. write(navigator. mime. Types[i]. type, " "); } </script>
More System Info function _get_version() } return Math. round(parse. Float(navigator. app. Version) * 1000; ( { function _get_os() } if (navigator. app. Version. index. Of("Win 95") > 0) return "WIN 95; " else if (navigator. app. Version. index. Of("Win 16") > 0) return "WIN 31; " else if (navigator. app. Version. index. Of("Mac") > 0) return "MAC; " else if (navigator. app. Version. index. Of("X 11") > 0) return "UNIX; " else return "UNKNOWN; " {
(. Sys Info (cont if (navigator. app. Name. substring(0, 8) == "Netscape } (" // if so, set the name variable appropriately browser. name = "NN; " // then parse navigator. app. Version to figure out what // version browser. version = _get_version(); // Then use app. Version again to determine the OS browser. os = _get_os(); }
(. Sys Info (cont else if (navigator. app. Name. substring(0, 9) == "Microsoft} (" browser. name = "MSIE; " browser. version = _get_version(); browser. os = "WIN 95"; } else { browser. name = navigator. app. Name; 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 = "Java. Script"> function start() { window. alert( paragraph. Text. inner. Text ); paragraph. Text. style. color = 'red'; paragraph. Text. inner. Text = "Virus has been installed !!" } </SCRIPT> </HEAD> An Example <BODY ONLOAD = "start()"> <FONT SIZE = '5'> <P ID = "paragraph. Text"> A new virus is now being install in your computer. </P></FONT> </BODY> </HTML>
Java. Script Object Hierarchy Window link anchor Document Form parent top self frames button radio checkbox select etc.
The window • Next, we will examine what can be done with a window • We follow Netscape properties and methods
Window Control • Window. open(address) – Navigation – Status – Address • Window. close(title)
(Window Properties (1 • closed Specifies whether a window has been closed • default. Status 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 • inner. Height Specifies the vertical dimension, in pixels, of the window's content area • inner. Width 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 • outer. Height Specifies the vertical dimension, in pixels, of the window's outside boundary • outer. Width Specifies the horizontal dimension, in pixels, of the window's outside boundary.
(Windows Properties (4 • page. XOffset Provides the current x-position, in pixels, of a window's viewed page • page. YOffset 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 • capture. Events Sets the window or document to capture all events of the specified type • clear. Interval Cancels a timeout that was set with the set. Interval method
(Window Methods (2 • clear. Interval Cancels a timeout that was set with the set. Interval method • clear. Timeout Cancels a timeout that was set with the set. Timeout method • close Closes the specified window • confirm Displays a Confirm dialog box with the specified message and OK and Cancel buttons • disable. External. Capture Disables external event capturing set by the enable. External. Capture method
(Window Methods (3 • enable. External. Capture 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 • handle. Event 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 • move. By Moves the window by the specified amounts • move. To 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 • release. Events Sets the window to release captured events of the specified type, sending the event to objects further along the event hierarchy • resize. By Resizes an entire window by moving the window's bottom-right corner by the specified amount • resize. To Resizes an entire window to the specified outer height and width
(Window Methods (5 • route. Event Passes a captured event along the normal event hierarchy • scroll Scrolls a window to a specified coordinate • scroll. By Scrolls the viewing area of a window by the specified amount • scroll. To Scrolls the viewing area of the window to the specified coordinates, such that the specified point becomes the top-left corner
(Window Methods (6 • set. Interval Evaluates an expression or calls a function every time a specified number of milliseconds elapses • set. Timeout 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 • alink. Color 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 • bg. Color 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 • fg. Color A string that specifies the TEXT attribute • form. Name 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 • last. Modified A string that specifies the date the document was last modified • layers Array containing an entry for each layer within the document • link. Color (vlink. Color) 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 • capture. Events Sets the document to capture all events of the specified type • close Closes an output stream and forces data to display • get. Selection Returns a string containing the text of the current selection • handle. Event Invokes the handler for the specified event • open Opens a stream to collect the output of write or writeln methods
(Document methods (2 • release. Events Sets the window or document to release captured events of the specified type, sending the event to objects further along the event hierarchy. • route. Event 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="Java. Script 1. 1<" //open a new window var 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 frames n. document. write('<frameset rows="50%, 50%" cols="50%, 50%">'); n. document. write('<frame name="f 1" src="about: blank">'); n. document. write('<frame name="f 2" src="about: blank">'); n. document. write('<frame name="f 3" src="about: blank">'); n. document. write('<frame name="f 4" 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. f 1, n. f 2, n. f 4, n. f 3; ( //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 = set. Timeout("change_one_frame()", 250; ( {
/>SCRIPT< />HEAD< --!>start the frame animation when the document is fully loaded- <>BODY on. Load="change_one_frame<"; () --!>Create a button to stop the animation with clear. Timeout<-- () --!>and close the window with close<-- () >FORM< > INPUT TYPE="button" VALUE="Stop" on. Click="if (timeout) clear. Timeout(timeout); if (!n. closed) n. close<"; () />FORM< />BODY< />HTML<
Javascript Events • Java. Script supports an event handling system – You can tell the browser to execute Java. Script 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 on. Focus • The general syntax is >TAG event. Handler="Java. Script Code<"
Handling Events • In Navigator 4. 0, Java. Script 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 click. Handler(evnt} ( // What goes here depends on how you want to handle the event. }
changing the text triggers “on. Change” event Java. Script Object Events window, e. g. browser’s viewable area document, e. g. home. html text 1 text 2 text 3 text 4 1 A 2 B 3 C 4 D 5 Form #1, e. g. user-input 6 7 8 Submit Button clicking the button triggers “on. Click” event
Events Example <BODY BGCOLOR=WHITE on. Unload="restore()"> <H 5>Hello - I am a very small page!</H 5> <SCRIPT> savewidth = window. inner. Width; saveheight = window. inner. Height; function restore() { window. inner. Width=savewidth; window. inner. Height=saveheight; } // Change the window size to be small window. inner. Width=300; window. inner. Height=50; document. bg. Color='cyan'; </SCRIPT>
Invocations • Three types of invocation: – Immediate – Deferred – Hybrid
Immediate Invocation <html><body> <h 1>Immediate invocation of Java. Script</h 1> <script language="Java. Script"> <!-- begin to hide code if necessary document. write("<hr><p>This page was updated on " + document. last. Modified + ". </p>") // end hiding code --> </script> </body></html>
Deferred Invocation <html><head> <script language="Java. Script"> function show. Date() { document. write("<hr><p>This page was updated on " + document. last. Modified + ". </p>") } </script> </head><body> <h 1>Deferred invocation of Java. Script</h 1> <form><input type="button" name="test" value="show. Date" on. Click="show. Date()"></form> </body></html>
>HTML< >HEAD><TITLE>Invocation Example</TITLE< >SCRIPT LANGUAGE = "Java. Script<" document. writeln("<FONT SIZE = '5' COLOR = 'blue<' Script at the head of the Document</FONT>"); function p 1() { window. confirm("Continue? "); document. writeln("<FONT SIZE = '5' COLOR = 'orange'> At function p 1</FONT>"); } function p 2() { document. writeln("<FONT SIZE = '5' COLOR = 'orange'> At function p 2</FONT>"); } </SCRIPT> </HEAD> Invocations Example
>BODY ONLOAD = "p 1<"() >FONT SIZE = '5 <' >P ID = "paragraph. Text<" Some Text in the document body />P< />FONT< >SCRIPT LANGUAGE = "Java. Script<" document. writeln("<FONT SIZE = '5' COLOR = 'orange<' At a script in the body</FONT>"); p 2(); </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 Java. Script immediately !
Deferred Invocation • • • on. Submit on. Click on. Blur on. Change on. Focus Located in the <Head<
Some More Events • on. Cut, on. Copy, on. Keydown, on. Key. Pressed • on. Drag, on. Drop, on. Double. Click, on. Mouse. Down, on. Mouse. Up, on. Drag. Over, on. Drag. Enter, on. Drag. Leave • on. Scroll, on. Resize, on. Select, on. Stop, on. Unload
Dialog Boxes • alert(“This is a Java. Script alert”) – user can “escape” to proceed • confirm(“Are you sure you want to submit this? ”) – user must respond yes or no • var my. Age = prompt(“Enter your age”) – user must enter an input string – resulting input is assigned to variable
Buttons • You can associate buttons with Java. Script events (buttons in HTML forms( <FORM> <INPUT TYPE=BUTTON VALUE="Don't Press Me" on. Click="alert('now you are in trouble!')“ > </FORM>
(Some Events (a small sample on. Un. Load on. Click on. Mouse. Up on. Mouse. Down on. Dbl. Click on. Mouse. Over Window events Button events Link events
on. Blur v. on. Click • 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 Java. Script 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
<script language="Java. Script"> 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> Sample Deferred Form Validation
Checking Fields 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!
Nee bro ded wse to p r r fr om event sub the mit ting ! <FORM METHOD=GET ACTION=foo. cgi The Form NAME=myform on. Submit="return(checkform())"> AGE: <INPUT TYPE=TEXT NAME=Age> <INPUT TYPE=SUBMIT> </FORM>
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 Java. Script to validate form fields!
Setting Cookies Function set. Cookie(name, value, expires) { document. cookie = name + “=“ + escape(value) + “; path=/”+ ((expires == null) ? “ “ ; expires=“ + expires. to. GMTString()); } var exp = new Date (); exp. set. Time(exp. get. Time() + (1000 * 60 * 24 * 31)); set. Cookie(“myname”, “myvalue”, exp);
Retrieving Cookies function get. Cookie(name) { var cname = name + “=“; var dc = document. cookie; if (dc. length > 0) { begin = dc. index. Of(cname); if (begin != -1) { begin += cname. length; end = dc. index. Of(“; ”, begin); if (end == -1) end = dc. length return unescape(dc. substring(begin, end)); } } return null; }
Moving Objects • Next, we give an example of moving objects on the screen
>HTML< >HEAD><TITLE>Moving Objects</TITLE> </HEAD> <BODY on. Load=“move. It()> <DIV ID="shape 1" STYLE="position: absolute; left: 100; top: 50; width: 300; height: 100; clip: rect(0, 300, 100, 0); background-color: red; layer-background-color: red; zindex: 2; "> </DIV> <DIV ID="shape 2" 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 move. It} () //Get the client window width and height on the initial load. if (first. Time} ( if (document. all} ( // Internet Explorer max. Height = document. body. client. Height-image. Height max. Width = document. body. client. Width-image. Width { else} // Netscape max. Height = window. inner. Height-image. Height max. Width = window. inner. Width-image. Width { first. Time = false chg. XBy = 1 chg. YBy = 1 {
//Get the current position of our image. if (document. all} ( // Internet Explorer top. Pos = document. all. mover. style. pixel. Top left. Pos = document. all. mover. style. pixel. Left { else} // Netscape top. Pos = document. mover. top left. Pos = document. mover. left {
//If any boundaries have been hit, change direction. // Upper Boundary if (top. Pos >= max. Height} ( chg. YBy = -1 { // Right Boundary if (left. Pos >= max. Width} ( chg. XBy = -1 { // Lower Boundary if (top. Pos <= 0} ( chg. YBy = 1 { // Left Boundary if (left. Pos <= 0} ( chg. XBy = 1 {
//Set the new position of the image. top. Pos += chg. YBy left. Pos += chg. XBy if (document. all} ( // Internet Explorer document. all. mover. style. pixel. Top = top. Pos document. all. mover. style. pixel. Left = left. Pos { else} // Netscape document. mover. top = top. Pos document. mover. left = left. Pos { //Iterate every 20 milliseconds set. Timeout("move. It()", 20( {
- Slides: 150