Presentation is loading. Please wait.

Presentation is loading. Please wait.

Javascript DBI – Representation and Management of Data on the Internet.

Similar presentations


Presentation on theme: "Javascript DBI – Representation and Management of Data on the Internet."— Presentation transcript:

1

2 Javascript DBI – Representation and Management of Data on the Internet

3 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

4 Overview (cont.) Scripts can manipulate "browser objects:" –HTML form elements –Images –Frames –etc. For security – cannot write to disk (when run on a client)

5 It is not Java Java : –compilation required –can create “stand alone” application –much more complex more commands more built-in functions object-oriented

6 Web browser HTML Page: …code..… Desktop access Internet HTML/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"

7 Example <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> An Hello World Example document.writeln(" Can't you find a better example than Hello World? );

8

9 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 standardEMCAscript

10 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

11 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

12 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

13 Non Used Reserved Words catch class const debugger default enum export extends finally import super try

14 Javascript Variables Untyped! Can be declared with var keyword: var foo; Can be created automatically by assigning a value: foo=1; blah="Hi Rakefet";

15 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

16 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

17 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!

18 Operators Arithmetic, comparison, assignment, bit wise, Boolean (pretty much just like Java) + - * / % ++ -- == != > = <= && || ! & | > += -= *= /= %=

19 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) {...}

20 Boolean Operators and if (true && true) {…} or if (true || false) {…} not if (! false) {...}

21 Using Variables var firstNumber = 11, secondNumber = 23, sum; sum = firstNumber + secondNumber; document.write(" The sum of " + firstNumber + " and " + secondNumber + " is "); document.write(" " + sum + " ");

22

23 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)

24 JavaScript’s Basic Constructs sequence (block) condition (selection) loop (iteration)

25 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 yourAverageAge yourAverageAge = metushelahAge - 98 var myObject = new Object("initial value") more statements here.. …..

26 JavaScript Constructs condition (selection) if (condition) {statements if true} else {statements if false} if (metushelahAge < yourAverageAge) { document.write (" its true that Metushelah is younger than most of you,") document.write (" computers never lie! ") }

27 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 "9") { alert("Please enter a valid number “ + oneChar + " is not valid.") }

28 Loops Example for (var counter = 1 ; counter <= 7 ; ++counter) { document.write(“ Now with font size " + counter + " “); }

29

30 Javascript Functions The keyword function used to define a function (subroutine): function add(x,y) { return(x+y); }

31 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

32 Functions Example 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 ); }

33 Enter a number <INPUT TYPE = "button" VALUE = "Calculate" ONCLICK = "fibonacciValue()" Fibonacci Value

34

35 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

36 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)

37 Global Functions (3) isFinite – given a numeric argument it returns true if the argument is not –NaN –Number.POSITIVE_INFINITY – Number.NEGATIVE_INFINITY

38 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()

39 Array Objects Arrays are supported as objects Attribute length Methods include: concat join pop push reverse sort

40 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

41 Array Example Code var a = [8,7,6,5]; for (i=0;i<a.length;i++) a[i] += 2; b = a.reverse();

42 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

43 Arrays Example function start() { var colors = ["red", "blue", "green"] printArray(colors); } function printArray( colorsArray ) { // prints the array but also modifies it for (var i in colorsArray) { var c = colorsArray[i]; document.writeln(" " + c + " "); colorsArray[i] = "gray"; }

44

45 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]);

46 Other Object Types String : manipulation methods Math : trig, log, random numbers Date : date conversions RegExp : regular expressions Number : limits, conversion to string

47 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

48 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()

49 Methods that Generate HTML anchor(name) – wraps the source with – big() – wraps the source with – blink() – wraps with – bold() – wraps the source with – fixed() – wraps the source with –

50 More Methods that Generate HTML fontcolor(color) – wraps with – fontsize(size) – wraps with – italic() – wraps with – link(url) –

51 More Methods that Generate HTML small() – wraps the source with – strike() – wraps the source with – sub() – wraps the source with – sup() – wraps the source with –

52 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)

53 Arrays Example 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; }

54

55

56 Predefined Objects In JavaScript the following objects are automatically created for you (always available) –document –navigator –screen –window

57 The document Object Many attributes of the current document are available via the document object: TitleReferrer URLImages FormsLinks Colors

58 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

59 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

60 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

61 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

62 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) }

63 Dynamic HTML HTML CSS Java Script HTML Dynamic HTML

64 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

65 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

66 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

67 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

68 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

69 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

70 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.

71 DOM Example <FORM NAME=myform ACTION= … Please Enter Your Age: And your weight: <FORM NAME=myform ACTION= … Please Enter Your Age: And your weight: From JavaScript you can get the age input field as: document.myform.age.value

72 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 += “ ”+document.all[loop].tagName; Only in In Microsoft Internet Explorer

73 Netscape vs. IE These features are specific to Netscape Navigator 4.0, and aren't supported by Microsoft: – tag – JavaScript Style Sheets – Bitstream fonts

74 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

75 The Solutions Use JavaScript to detect the browser – –<!-- –ns4 = (document.layers)? true:false –ie4 = (document.all)? true:false –function init() { –if (ns4) block = document.blockDiv –if (ie4) block = blockDiv.style –} –//--> – The document.layers object is specific to Netscape 4.0, while the document.all object is specific to IE 4.0.

76 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

77 window plugins document frames history navigator location event screen all collections anchors applets body embeds images forms filters links plugins styleSheets scripts objects In IE

78 In Netscape

79 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

80 for (prop in navigator) { document.write(prop + " -> " + navigator[prop], " "); } document.write(" Plugins "); for (i=0; i<navigator.plugins.length; i++) { document.write(navigator.plugins[i].name, " "); } document.write(" Mime Types "); for (i=0; i<navigator.mimeTypes.length; i++) { document.write(navigator.mimeTypes[i].type, " "); }

81

82 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"; }

83 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(); }

84 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(); }

85 Sys Info (cont.) with (browser) { document.write(" Name=", name); document.write(" Version=", version); document.write(" OS=", os); }

86 Arrays Example function start() { window.alert( paragraphText.innerText ); paragraphText.style.color = 'red'; paragraphText.innerText = "Virus has been installed !!" } A new virus is now being install in your computer. An Example

87

88

89 JavaScript Object Hierarchy Window Document Form parent top self frames link anchor button radio checkbox select etc.

90 The window Next, we will examine what can be done with a window We follow Netscape properties and methods

91 Window Control Window.open(address) –Navigation –Status –Address Window.close(title)

92 Window Properties (1) closed Specifies whether a window has been closedclosed defaultStatus Reflects the default message displayed in the window's status bardefaultStatus document Contains information on the current document, and provides methods for displaying HTML output to the userdocument frames An array reflecting all the frames in a windowframes history Contains information on the URLs that the client has visited within a windowhistory

93 Windows Properties (2) innerHeight Specifies the vertical dimension, in pixels, of the window's content areainnerHeight innerWidth Specifies the horizontal dimension, in pixels, of the window's content areainnerWidth length The number of frames in the windowlength location Contains information on the current URLlocation locationbar Represents the browser window's location barlocationbar

94 Windows Properties (3) menubar Represents the browser window's menu barmenubar name A unique name used to refer to this windowname opener Specifies the window name of the calling document when a window is opened using the open methodopener outerHeight Specifies the vertical dimension, in pixels, of the window's outside boundaryouterHeight outerWidth Specifies the horizontal dimension, in pixels, of the window's outside boundary.outerWidth

95 Windows Properties (4) pageXOffset Provides the current x-position, in pixels, of a window's viewed pagepageXOffset pageYOffset Provides the current y-position, in pixels, of a window's viewed pagepageYOffset parent A synonym for a window or frame whose frameset contains the current frameparent personalbar Represents the browser window's personal bar (also called the directories bar)personalbar

96 Window Properties (5) scrollbars Represents the browser window's scroll barsscrollbars self A synonym for the current windowself status Specifies a priority or transient message in the window's status barstatus statusbar Represents the browser window's status barstatusbar toolbar Represents the browser window's tool bartoolbar top A synonym for the topmost browser windowtop window A synonym for the current windowwindow

97 Window Methods (1) alert Displays an Alert dialog box with a message and an OK buttonalert back Undoes the last history step in any frame within the top-level windowback blur Removes focus from the specified objectblur captureEvents Sets the window or document to capture all events of the specified typecaptureEvents clearInterval Cancels a timeout that was set with the setInterval methodclearInterval setInterval

98 Window Methods (2) clearInterval Cancels a timeout that was set with the setInterval methodclearInterval setInterval clearTimeout Cancels a timeout that was set with the setTimeout methodclearTimeout setTimeout close Closes the specified windowclose confirm Displays a Confirm dialog box with the specified message and OK and Cancel buttonsconfirm disableExternalCapture Disables external event capturing set by the enableExternalCapture methoddisableExternalCapture enableExternalCapture

99 Window Methods (3) enableExternalCapture Allows a window with frames to capture events in pages loaded from different locations (servers)enableExternalCapture find Finds the specified text string in the contents of the specified windowfind focus Gives focus to the specified objectfocus forward Loads the next URL in the history listforward handleEvent Invokes the handler for the specified eventhandleEvent

100 Window Methods (3) home Points the browser to the URL specified in preferences as the user's home pagehome moveBy Moves the window by the specified amountsmoveBy moveTo Moves the top-left corner of the window to the specified screen coordinatesmoveTo open Opens a new web browser windowopen print Prints the contents of the window or frameprint

101 Window Methods (4) prompt Displays a Prompt dialog box with a message and an input fieldprompt releaseEvents Sets the window to release captured events of the specified type, sending the event to objects further along the event hierarchyreleaseEvents resizeBy Resizes an entire window by moving the window's bottom-right corner by the specified amountresizeBy resizeTo Resizes an entire window to the specified outer height and widthresizeTo

102 Window Methods (5) routeEvent Passes a captured event along the normal event hierarchyrouteEvent scroll Scrolls a window to a specified coordinatescroll scrollBy Scrolls the viewing area of a window by the specified amountscrollBy scrollTo Scrolls the viewing area of the window to the specified coordinates, such that the specified point becomes the top-left cornerscrollTo

103 Window Methods (6) setInterval Evaluates an expression or calls a function every time a specified number of milliseconds elapsessetInterval setTimeout Evaluates an expression or calls a function once after a specified number of milliseconds has elapsedsetTimeout stop Stops the current downloadstop

104 The document Next, we will examine what can be done with a document We follow Netscape properties and methods

105 Properties of document alinkColor A string that specifies the ALINK attributealinkColor anchors An array containing an entry for each anchor in the documentanchors applets An array containing an entry for each applet in the documentapplets bgColor A string that specifies the BGCOLOR attributebgColor cookie Specifies a cookiecookie

106 Document properties (2) domain Specifies the domain name of the server that served a documentdomain embeds An array containing an entry for each plug-in in the documentembeds fgColor A string that specifies the TEXT attributefgColor formName A separate property for each named form in the documentformName

107 Document properties (3) forms An array a containing an entry for each form in the documentforms images An array containing an entry for each image in the documentimages lastModified A string that specifies the date the document was last modifiedlastModified layers Array containing an entry for each layer within the documentlayers linkColor (vlinkColor) A string that specifies the LINK (VLINK) attribute

108 Document properties (4) links An array containing an entry for each link in the documentlinks plugins An array containing an entry for each plug-in in the documentplugins referrer A string that specifies the URL of the calling documentreferrer title A string that specifies the contents of the TITLE tagtitle URL A string that specifies the complete URL of a documentURL

109 Document methods (1) captureEvents Sets the document to capture all events of the specified typecaptureEvents close Closes an output stream and forces data to displayclose getSelection Returns a string containing the text of the current selectiongetSelection handleEvent Invokes the handler for the specified eventhandleEvent open Opens a stream to collect the output of write or writeln methodsopen

110 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.releaseEvents routeEvent Passes a captured event along the normal event hierarchyrouteEvent write Writes one or more HTML expressions to a document in the specified windowwrite writeln Writes one or more HTML expressions to a document in the specified window and follows them with a newline characterwriteln

111 // 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(' ');

112 // 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;

113

114 function change_one_frame() { // dynamically output the HTML necessary to set the background color windows[f].document.write(' '); 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); }

115 <INPUT TYPE="button" VALUE="Stop" onClick="if (timeout) clearTimeout(timeout); if (!n.closed) n.close();">

116 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

117 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

118 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

119 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. }

120 JavaScript Object Events window, e.g. browser’s viewable area document, e.g. home.html text1text2 text4text3 ABCD 12345678 Submit Button Form #1, e.g. user-input changing the text triggers “onChange” event clicking the button triggers “onClick” event

121 Events Example Hello - I am a very small page! savewidth = window.innerWidth; saveheight = window.innerHeight; function restore() { window.innerWidth=savewidth; window.innerHeight=saveheight; } // Change the window size to be small window.innerWidth=300; window.innerHeight=50; document.bgColor='cyan';

122 Invocations Three types of invocation: –Immediate –Deferred –Hybrid

123 Immediate Invocation Immediate invocation of JavaScript <!-- begin to hide code if necessary document.write(" This page was updated on " + document.lastModified + ". ") // end hiding code -->

124 Deferred Invocation function showDate() { document.write(" This page was updated on " + document.lastModified + ". ") } Deferred invocation of JavaScript

125 Invocation Example document.writeln(" Script at the head of the Document "); function p1() { window.confirm("Continue?"); document.writeln(" At function p1 "); } function p2() { document.writeln(" At function p2 "); } Invocations Example

126 Some Text in the document body document.writeln(" At a script in the body "); p2(); After the script in the body.

127

128

129 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!

130 Deferred Invocation onSubmit onClick onBlur onChange onFocus Located in the

131 Some More Events onCut, onCopy, onKeydown, onKeyPressed onDrag, onDrop, onDoubleClick, onMouseDown, onMouseUp, onDragOver, onDragEnter, onDragLeave onScroll, onResize, onSelect, onStop, onUnload

132 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

133 Buttons You can associate buttons with JavaScript events (buttons in HTML forms) <INPUT TYPE=BUTTON VALUE="Don't Press Me" onClick="alert('now you are in trouble!')“ > <INPUT TYPE=BUTTON VALUE="Don't Press Me" onClick="alert('now you are in trouble!')“ >

134 Some Events (a small sample) onUnLoad onLoad onClick onMouseUp onMouseDown onDblClick onMouseOver Window events Button events Link events

135 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

136 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

137 Sample Deferred Form Validation 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); }

138 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!

139 The Form <FORM METHOD=GET ACTION=foo.cgi NAME=myform onSubmit="return(checkform())"> AGE: Needed to prevent the browser from submitting!

140 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!

141 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);

142 Retrieving Cookies function 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.length return unescape(dc.substring(begin, end)); } return null; }

143 Moving Objects Next, we give an example of moving objects on the screen

144 Moving Objects

145

146 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 }

147 //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 }

148 //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 }

149 //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) }

150


Download ppt "Javascript DBI – Representation and Management of Data on the Internet."

Similar presentations


Ads by Google