1 Representation and Management of Data on the Internet
Dec 23, 2015
1
Representation and Management of Data on the Internet
2
Dynamic HTML
HTML
CSSJava Script
HTML HTML
Dynamic HTML
3
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 elements that can be manipulated
– exposing those elements to a scripting language
– the script performs the manipulations
4
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
5
JavaScript (+)
• JavaScript can: – 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
6
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
7
We Will Show
• Getting information on the browser
• Document manipulations– Content– Style
• Events handling
• Forms validation
• Using cookies
8
Page is loaded DOM tree is created
events
9
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, change the Web page
10
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.
document.form[1].text[2].value
document.myform.book.value
11
DOM Example<FORM NAME=“myform” ACTION=…>Please enter Your age:<INPUT TYPE=“TEXT” NAME=“age”><BR>and the name of your favorite book:<INPUT TYPE=“TEXT” NAME=“book”><BR></FORM>
• From JavaScript you can get the age input field as: • document.myform.age.value
12
Different Browsers
Different browser Different JavaScript
Internet Explorer JavaScript
NetscapeJavaScript
13
The Solutions• Use JavaScript to detect the browser
<SCRIPT LANGUAGE="JavaScript"><!--ns4 = (document.layers)? true:falseie4 = (document.all)? true:falsefunction init() {
if (ns4) block = document.blockDivif (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
14
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;
In IE only!!!
15
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
16
In Netscape
17
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
18
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
19
<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>
20
21
More System Infofunction _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("Win98") > 0)
return "WIN98"; else if (navigator.appVersion.indexOf("Mac") > 0)
return "MAC"; else if (navigator.appVersion.indexOf("X11") > 0)
return "UNIX"; else return "UNKNOWN";}
22
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();
}
23
Sys Info (cont.)
else if (navigator.appName.substring(0,9) == "Microsoft") {
browser.name = "MSIE";
browser.version = _get_version();
browser.os = "WIN98";
}
else {
browser.name = navigator.appName;
browser.version = _get_version();
browser.os = _get_os();
}
24
Sys Info (cont.)
with (browser) {
document.write("<p>Name=", name);
document.write("<p>Version=", version);
document.write("<p>OS=", os);
}
25
Information to User
alert
confirm
prompt
26
<HTML><HEAD><TITLE>Dialogs Example</TITLE></HEAD>
<BODY><FONT SIZE = '5'> <P>Hello, this page will help you to install viruses in your computer.<SCRIPT LANGUAGE = "JavaScript">num = prompt("Enter the number of viruses to install", 10);document.write("You have asked to install " + num + " viruses.");</SCRIPT><P>First, you should confirm the installation.<P><SCRIPT LANGUAGE = "JavaScript">if (confirm("Are you ready for the virus installation?")) alert("Starting the virus installation.")</SCRIPT>Thank you for installing our viruses in your computer.</FONT></BODY></HTML>
27
Manipulating Objects
• You can replace images in the page dynamically by setting their source
28
29
<HTML><HEAD><TITLE>Imagess Example</TITLE><SCRIPT LANGUAGE = "JavaScript">
pageImages;imgNo;
function start() {pageImages = new Array('dino.gif',
'monkey.gif', 'witch.gif');imgNo = 0;
}
function replaceImage() {imgNo = (imgNo + 1) % pageImages.length;document.image.src = pageImages[imgNo];}
}</SCRIPT></HEAD>
30
<BODY onLoad="start()"><FONT SIZE = '5'> This is a picture:<IMG SRC="dino.gif" name="image"><BR>Do you want to replace the picture?<FORM NAME="replacePicture"><INPUT TYPE="button" VALUE="Yes" onClick="replaceImage()"></FORM>
</FONT></BODY></HTML>
31
Opening a New Window
<FORM><INPUT TYPE="button" VALUE="Open Second Window" onClick="msgWindow=window.open(‘doc2.html',
'window2', 'resizable=no,width=200,height=200')"><P><INPUT TYPE="button" VALUE="Close Second Window" onClick="msgWindow.close()"></FORM>
Why does a window need a name?
32
Opening a New Window
<FORM><INPUT TYPE="button" VALUE="Open Second Window" onClick="msgWindow=window.open('','window2', 'resizable=no,width=200,height=200')"><P><A HREF="doc2.html" TARGET="window2"> Load a file into window2</A><P><INPUT TYPE="button" VALUE="Close Second Window" onClick="msgWindow.close()"></FORM>
33
Javascript Events
• JavaScript supports an event handling system– You can tell the browser to execute JavaScript
commands when some event occurs
• Events usually occur due to users actions, for example, – clicking a button,
– changing a text field
– moving the mouse over a link
– …
34
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">
35
<HEAD><SCRIPT>function compute(f) { if (confirm("Are you sure?")) f.result.value = eval(f.expr.value) else alert("Please come back again.")}</SCRIPT></HEAD><BODY><FORM>Enter an expression:<INPUT TYPE="text" NAME="expr" SIZE=15 ><INPUT TYPE="button" VALUE="Calculate"
onClick="compute(this.form)"><BR>Result:<INPUT TYPE="text" NAME="result" SIZE=15 ></FORM></BODY>
36
<SCRIPT LANGUAGE="JavaScript">function fun1() { ...}function fun2() { ...}</SCRIPT><FORM NAME="myForm"><INPUT TYPE="button" NAME="myButton" onClick="fun1()"></FORM><SCRIPT>document.myForm.myButton.onclick=fun2</SCRIPT>
Resetting the eventHandler
37
Event Handlers
onAbort, onBlur, onChange, onClick, onDragDrop, onError, onFocus, onKeyDown,
onKeyPress, onKeyUp, onLoad, onMouseDown, onMouseMove, onMouseUp,
onMouseOver, onMove, onResize, onSelect, onSelect, onSubmit, onUnload
38
Events Related to DOM Objects
onUnLoad
onLoad
onClick
onMouseUp
onMouseDown
onClick
onMouseOver
Window events
Button events
Link events
39
Event Object• Each event has an event object associated
with it• The event object provides information
about the event, such as – the type of event, 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
40
The Event Object Properties
• target – String representing the object to which the event was originally sent
• type – String representing the event type
• data – Returns an array of strings containing the URLs of the dropped objects (DragDrop event)
41
The Event Object Properties
• layerX• layerY• width – Represents the width of the
window or frame
• height – Represents the height of the window or frame.
42
The Event Object Properties
• pageX – Number specifying the cursor's horizontal position in pixels, relative to the page
• pageY – Number specifying the cursor's vertical position in pixels relative to the page
• screenX – Number specifying the cursor's horizontal position in pixels, relative to the screen
• screenY – Number specifying the cursor's vertical position in pixels, relative to the screen
43
Event Properties
• which – Number specifying either the mouse button that was pressed or the ASCII value of a pressed key (For a mouse, 1 is the left button, 2 is the middle button, and 3 is the right button)
44
Event Capturing
• Events are “falling” down the DOM tree
• At each level they can be – captured, – handled, – routed
45
Event Capturing
• captureEvents – captures events of the specified type
• releaseEvents – ignores the capturing of events of the specified type
• routeEvent – routes the captured event to a specified object
• handleEvent – handles the captured event (Not a method of layer)
46
Example, Capturing Click Event
1. Set up the window to capture all Click events
2. Define a function that handles the event
3. Register the function as the window's event handler for that event
47
Capturing the Event
window.captureEvents(Event.CLICK);
window.captureEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP)
48
Defining a Function that Handles the Event
function processClicks(event) { ... // statements to handle event
}
window.captureEvents(Event.CLICK)
window.onclick = processClicks
49
Routing the Event
function processClicks(e) { alert(“Event is captured and routed") routeEvent(e)}
50
Invocations
• Three types of invocation:– Immediate– Deferred– Hybrid
51
Immediate Invocation
<html>
<body>
<h1>Immediate invocation of JavaScript</h1>
<script language="JavaScript">
document.write("<hr><p>This page was updated on " + document.lastModified + ".</p>")
</script>
</body>
</html>Code is interpreted and immediately executed
52
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>
Code is executed when thefunction is called (upon event)
53
<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(“At p1()");
}
function p2() {
document.writeln("<FONT SIZE = '5' COLOR = ‘red'>
At function p2</FONT>");
}
</SCRIPT>
</HEAD> Invocations Example
1
54
<BODY onLoad = "p1()"><FONT SIZE = '5‘ COLOR=‘magenta’> <P ID = "paragraphText">Some Text in the document body</P></FONT>
<SCRIPT LANGUAGE = "JavaScript">document.writeln("<FONT SIZE = '5' COLOR = ‘purple'> At a script in the body</FONT>");
p2();</SCRIPT><P><BIG>After the script in the body.</BIG>
</BODY></HTML>
6
2
34
5
55
56
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!
57
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
58
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>
59
Checking Fields
function checkform() { if (document.myform.age.value == "") { alert("You need to specify an age"); return(false); } else { return(true); }}
Does not have to get the for as a parameter
60
The Form<FORM METHOD=‘GET’ ACTION=‘myFormServlet’ NAME=‘myform’
onSubmit="return(checkform())">
AGE: <INPUT TYPE=“TEXT” NAME=“Age”>
<INPUT TYPE=“SUBMIT”>
</FORM>
61
Important Note about Form Validation
• It's a good idea to make sure the user fills out the form before submitting
• However, users can bypass your form – they can create requests manually (or their own forms)
• Your server programs cannot rely (solely) on Client-Side JavaScript to validate form fields!
62
Cookies
• Allow to store persistent data in a file cookies.txt
• Provide a way to maintain information between client requests (sessions)
• A cookie is added in the formatname=value;expires=expDate;
• If expires is missing, the cookie last for the current session only
63
Limitation on Cookies
• Cookies have these limitations: – 300 total cookies in the cookie file – 4 Kbytes per cookie, (for the sum of both the
cookie's name and value)– 20 cookies per server or domain
64
Setting Cookiesfunction 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);
65
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.length return unescape(dc.substring(begin, end));}
}return null;}
66
Example
67
Example
after dragging!
68
The Code<HTML><HEAD><TITLE>Draging Layers on the Screen </TITLE> </HEAD>
<STYLE TYPE="text/css">LAYER {align: left; text-align: center; border-width:4pt; border-style:outset; border-color: orange}</STYLE>
<BODY><H1>An Example of Draging Layers on the Screen of the Browser</H1><font color='red'>This example works on Netscape!</font>
69
<LAYER NAME="layer1" STYLE="position:absolute; left:0; top:100; width:300; height:100; background-color:orange; layer-background-color:yellow; border-color: yellow"><BIG>I like Oranges</BIG><P>Kah Od Tapuz, Ata yodea Lama</P><BR></LAYER>
<LAYER NAME="layer2" STYLE="position:absolute; left:30; top:50; width:300; height:100; background-color:yellow; layer-background-color:orange"><BIG>I like Bananas</BIG><P>Banana, Pitsesat Energia Tseuba</P><BR></LAYER>
</BODY>
70
<SCRIPT>var posLeft = 0;var posTop = 0;maxZindex = 2;currentLayer = document.layers[1];
for (var i=0; i<document.layers.length; ++i) { document.layers[i].document.captureEvents( Event.MOUSEUP|Event.MOUSEDOWN|Event.MOUSEDRAG); document.layers[i].document.onMouseUp=endDrag;}
document.layers[0].document.onmousedown=beginDrag0;document.layers[1].document.onmousedown=beginDrag1;
71
function beginDrag0(e) { beginDragObj(e, document.layers[0]);}
function beginDrag1(e) { beginDragObj(e, document.layers[1]);}
72
function beginDragObj(e, layer) { if (e.which == 3) { if (maxZindex > layer.zIndex){ layer.zIndex = (++maxZindex); } } else if (e.which == 1) { window.status = "Begin Drag" currentLayer = layer currentLayer.document.captureEvents(
Event.MOUSEMOVE); currentLayer.document.onmousemove=drag;
posLeft = e.pageX; posTop = e.pageY; } return false;}
73
function drag(e) { currentLayer.pageX += (e.pageX - posLeft); currentLayer.pageY += (e.pageY - posTop); posLeft = e.pageX; posTop = e.pageY; window.status = "Position(" + currentLayer.pageX + "," + currentLayer.pageY + ")" return false;}
function endDrag(e) { window.status="End Drag" currentLayer.document.onmousemove=0; currentLayer.document.releaseEvents(Event.MOUSEMOVE); currentLayer = null; return false;}</SCRIPT></HTML>
74
Window Control
• Window.open(address)– Navigation
– Status
– Address
• Window.close(title)
• Next, you are given a list of important methods and properties of window and document
75
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
76
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
77
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.
78
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)
79
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
80
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
81
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
82
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
83
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
84
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
85
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
86
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
87
The document
• Next, we will examine what can be done with a document
• We follow Netscape properties and methods
88
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
89
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
90
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
91
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
92
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
93
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
94
An Example
• The following is an example of using frames in side a window
• The example does not work in Netscape
95
<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>');
96
// 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;
97
98
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);}
99
</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>