1 Dynamic HTML (DHTML) Representation and Management of Data on the Internet.

Post on 15-Jan-2016

224 views 0 download

transcript

1

Dynamic HTML (DHTML)Dynamic HTML (DHTML)

Representation and

Management of Data on the

Internet

2

What is Dynamic HTMLWhat 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

3

Why Do We Need DHTML?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

4

JavaScript (+)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

5

JavaScript (-)JavaScript (-)

• What JavaScript cannot do:

– No graphics capabilities

– No reading/writing of files on the client

side

– No multithreading

6

We Will ShowWe Will Show

• Getting information on the browser

• Document manipulations– Content

– Style

• Events handling

• Forms validation

• Using cookies

7

Dynamic HTML Object Dynamic HTML Object Model (DOM)Model (DOM)

• 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

8

The Object ModelThe 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

9

DOM ExampleDOM 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

10

In Netscape

11

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

12

Different BrowsersDifferent Browsers

Different browser Different JavaScript

Internet Explorer JavaScript

NetscapeJavaScript

13

A Solution: Use JavaScript to A Solution: Use JavaScript to Detect the browserDetect the browser

• The document.layers object is specific to

Netscape 4.0, while the document.all

object is specific to IE 4.0 <SCRIPT LANGUAGE="JavaScript">

<!--

ns4 = (document.layers)? true:false

ie4 = (document.all)? true:false

function init() {

if (ns4) doSomethingNetscape()

if (ie4) doSomeThingExplorer()

}

//-->

</SCRIPT>

14

Collections Collections allall and and childrenchildren

• 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;

15

Window ObjectWindow Object

16

The Window ObjectThe Window Object

• Built-in object called window

• Many methods and properties for

useful features

– opening and closing other windows

– timers

– dialog boxes

– manipulating the status bar

17

Opening and Closing Opening and Closing WindowsWindows

• To open a window, use the open method.

Gets:

– url to be opened

– name of new window

– window characteristics

• Returns a window variable

• To close a window, call "close" on the

window variable

18

<html><head><title>Opening Windows</title></head><body><form><input type="button" value="Open Window"

onClick="awindow=window.open('HelloWorld.html','window2','resizable=nowidth=200,height=200')">

<P><input type="button" value="Close Window"

onClick="awindow.close()"></form><a href="ArrayColors.html" target="window2">

Load something else into window2</a></body></html>

RESULT

What is the difference between awindow and window2?

19

Using TimersUsing Timers

• 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

• clearInterval Cancels a timeout that was set with

the setInterval method

• clearTimeout Cancels a timeout that was set with

the setTimeout method

20

<html><head><title>OnLoad Example></title><script language="JavaScript">var seconds=0

function startTimer() { window.setInterval("updateTime()", 1000);}

function updateTime() { a = document.getElementById("soFar"); soFar.innerText=++seconds}</script></head><body onload="startTimer()">Seconds that you have spent looking at this page:<a id="soFar" style="font-weight: bold">0</a></body></html>

RESULT

21

Window Dialog BoxesWindow Dialog Boxes

alert:

confirm: returns true or false

prompt:returns value entered ornull if no value was entered

22

<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.") document.write("Thank you for installing our viruses in" + " your computer.")}</SCRIPT></FONT></BODY></HTML> RESULT

23

Status BarStatus Bar

• change window.status to change the

status bar value

• change window.defaultStatus to

change the default value of the status

bar

• recall fibonacci example from last

week

24

Information about the Information about the BrowserBrowser

• 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

25

Location and HistoryLocation and History

• location:

– properties: hostname

– methods: reload(url), replace(url)

• history: (an array of urls)

– properties: current, next, previous

– methods: go(int)

26

<html> <head><title>Navigator Properties</title><script language="JavaScript">document.write("<h1>Properties</h1>")for (prop in navigator) document.write(prop + " = " + navigator[prop] + "<br>")document.write("<h1>Properties</h1>")for (i=0; i < navigator.plugins.length; i++) document.write(navigator.plugins[i].name + "<br>")

document.write("<h1>Mime Types</h1>")for (i=0; i < navigator.mimeTypes.length; i++) document.write(navigator.mimeTypes[i].type + "<br>")

</script></head><body></body> </html>

RESULT

27

28

More System InfoMore System Info

• Some other navigator properties:

– navigator.appVersion

– navigator.appName

<html> <head><title>Navigator Properties</title>

<script language="JavaScript">

with (navigator) {

document.write("<p>AppName=", appName);

document.write("<p>Version=", appVersion);

}</script></head><body></body> </html> RESULT

29

Changing the Content of a Changing the Content of a PagePage

30

Manipulating ObjectsManipulating Objects

• We saw that you can replace text

(recall the timer example)

• Here is an expanding list, using this

idea

RESULT

31

<HTML><HEAD><TITLE>An Hello World Example</TITLE><SCRIPT LANGUAGE = "JavaScript">var expanded = -1var unexpandedText=[ "<a onclick='expand(0)'>+</a> Item 1 of the Menu", " <a onclick='expand(1)'>+</a> Item 2 of the Menu", " <a onclick='expand(2)'>+</a> Item 3 of the Menu"]var expandedText=[ "<a onclick='expand(0)'>=</a> Item 1 of the Menu<ul> " + "<li> SubItem 1 </li> <li> SubItem 2 </li> </ul>", "<a onclick='expand(1)'>=</a> Item 2 of the Menu<ul> " + "<li> SubItem 1b </li></ul>", "<a onclick='expand(2)'>=</a> Item 3 of the Menu<ul> " + "<li> SubItem 2b </li> </ul>"]

32

function expand(num) { if (expanded != -1) { var a = document.getElementById("item" + expanded); a.innerHTML = unexpandedText[expanded] } if (expanded == num) expanded = -1 else expanded = num if (expanded != -1) { var b = document.getElementById("item" + num); b.innerHTML = expandedText[num] }}</SCRIPT><STYLE> ul {list-style-type:none} a {color:red}</STYLE></HEAD>

33

<BODY><ul> <li id = "item0">

<a onclick="expand(0)">+</a> Item 1 of the Menu </li> <li id = "item1">

<a onclick="expand(1)">+</a> Item 2 of the Menu </li> <li id = "item2">

<a onclick="expand(2)">+</a> Item 3 of the Menu </li></ul> </BODY></HTML>

RESULT

34

ProblemProblem

• In the previous example, when the

mouse was over the + and =, the

mouse was not a “hand”.

• To make the normal hand, the a

element must be a link. Where to?

35

Solution: JavaScript Solution: JavaScript ProtocolProtocol

• You can href to something of the form javascript:code

• Then, the code is performed. If the code does not return a value, nothing more is done

• If the code returns a value, the value is considered a new URL which will be loaded.

• Example:– <A HREF="javascript:alert('Hello World'); return

‘HelloWorld.html’">Hello World</A>

– <A HREF=“javascript:void(0)”> … </A>

• The keyword void makes sure that nothing is returned

36

Solution: JavaScript Solution: JavaScript ProtocolProtocol

• To fix our example: add href to

javascript:void(0) to each link

• Add additional style declarations,

– a:link {TEXT-DECORATION:none; COLOR: red}

– a:visited {TEXT-DECORATION:none; COLOR: red}

– a:active {TEXT-DECORATION:none; COLOR: red}

– a:hover {TEXT-DECORATION:none; COLOR: red}

RESULT

37

Manipulating ObjectsManipulating Objects

• You can also replace images in the

page dynamically by setting their

source

38

<HTML><HEAD><TITLE>Images Example</TITLE><SCRIPT LANGUAGE = "JavaScript">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><BODY><FONT SIZE = '5'> This is a picture:<IMG SRC="dino.gif" name="image"><BR><FORM NAME="replacePicture"><INPUT TYPE="button" VALUE="Replace the Picture"

onClick="replaceImage()"></FORM></FONT></BODY></HTML>

RESULT

39

Changing the StyleSheetChanging the StyleSheet

• You have seen that you can define the

style of a page in an external CSS page

• How can we allow the user to change

the style, i.e., change the CSS used?

• Why would we want this?

40

Changing the StyleSheetChanging the StyleSheet

• Define the stylesheets in your document:

– <LINK REL="stylesheet" ID HREF="js_oud.css"

DISABLED>

– <LINK REL="stylesheet" HREF="js.css">

• For some browsers, this will disable the first

style sheet. For it to work on netscape, add:if (document.getElementsByTagName)

document.getElementsByTagName('link')[0].disabled =

true;

41

Changing the StyleSheetChanging the StyleSheetfunction changeCSS(nr) {

if (document.getElementsByTagName)

x = document.getElementsByTagName('link');

else if (document.all) x = document.all.tags('link');

else {

alert('This script does not work in your browser');

return;

}

nr--;

for (var i=0;i<x.length;i++) {

dis = !(i == nr);

x[i].disabled = dis;

} }RESULT

42

QuestionQuestion

• How would you create a banner ad that

changes automatically every 5 seconds?

• How would create banner ads that were also

a hyperlink to a site that change

automatically every 5 seconds?

• How would you create a picture that

changes when your mouse is over it? (i.e., a

rollover image)

43

Event ModelEvent Model

44

Javascript EventsJavascript 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

– …

45

Events on TAGSEvents 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">

46

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

47

<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

48

Event HandlersEvent Handlers

onAbort, onBlur, onChange, onClick, onDragDrop, onError, onFocus, onKeyDown,

onKeyPress, onKeyUp, onLoad, onMouseDown, onMouseMove, onMouseUp,

onMouseOver, onMove, onResize, onSelect, onSelect, onSubmit, onUnload

49

Events Related to DOM Events Related to DOM ObjectsObjects

onUnLoad

onLoad

onClick

onMouseUp

onMouseDown

onClick

onMouseOver

Window events

Button events

Link events

50

Event ObjectEvent 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

51

The Event Object The Event Object PropertiesProperties

• Events have many properties, and these

differ according to the browser.

• Most Interesting:

– What is the type of event?

– Which HTML element is the target of the event?

– Which key was pressed during the event?

– Which mouse button was pressed during the

event?

– What was the mouse position during the event?

52

Type of EventType of Event

function eventType(e) {

if (!e) var e = window.event;

alert(e.type);

}

53

Target of the EventTarget of the Event

W3C/Netscape: target, Explorer:srcElement

function eventTarget(e) {

var targ;

if (!e) var e = window.event;

if (e.target) targ = e.target;

else if (e.srcElement) targ = e.srcElement; alert(targ);

}

54

Key PressedKey Pressed

Function eventKey(e) {

var code;

if (!e) var e = window.event;

if (e.keyCode) code = e.keyCode;

else if (e.which) code = e.which;

var character = String.fromCharCode(code); alert('Character was ' + character);

}

55

Mouse Button PressedMouse Button Pressed

function eventMouse(e) {

var rightclick;

if (!e) var e = window.event;

if (e.which) rightclick = (e.which == 3);

else if (e.button) rightclick = (e.button == 2);

alert('Rightclick: ' + rightclick); // true or false

}

Button values (W3C): left=0, middle=1, right=2

Button values (Microsoft): left=1 middle=4 right=2

56

Mouse PositionMouse Position

A complete mess. Combination of the values:

1. clientX,clientY

2. layerX,layerY

3. offsetX,offsetY

4. pageX,pageY

5. screenX,screenY

6. x,y

57

Order of Event HandlingOrder of Event Handling

• Suppose that Element 1 and Element 2

both have onClick handlers and we

click in Element 2. Which handler is

called?

Element 2

Element 1

58

Order of Event HandlingOrder of Event Handling

• Events are first "captured" from most

general to least general

• Events are then "bubbled" from most

specific to least specific

Element 2

Element 1

59

Order of Event HandlingOrder of Event Handling

• Registering event handlers for capturing

phase is complex

• Default registration is for bubbling phase

• So, event handler of element 2 will be

called, and then the event handler of

element 1

• How do we stop an event from bubbling up?

60

Order of Event HandlingOrder of Event Handling

• To stop the bubbling:

function stopEvent(e) {

if (!e) var e = window.event;

e.cancelBubble = true; // Microsoft

if (e.stopPropagation) e.stopPropagation();

//W3C

}

61

<html> <head><title>Bubble Example</title><script language="JavaScript">function f1() { alert("In f1")}function f2() { alert("In f2")}function f3(e) { alert("In f3") if (!e) var e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } </script></head>

62

<body onClick="f1()"><p onClick="f2()"> Bubbling continues in this paragraph</p><p onClick="f3()"> Bubbling stops in this paragraph</p></body> </html>

RESULT

63

Form ValidationForm Validation

64

Form ValidationForm 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 fields

• If values are illegal, you can prevent

the form information from being sent

65

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

66

Checking FieldsChecking 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 form as a parameter

67

The FormThe Form

<FORM METHOD=‘GET’

ACTION=‘myFormServlet’ NAME=‘myform’

onSubmit="return(checkform())">

AGE: <INPUT TYPE=“TEXT” NAME=“Age”>

<INPUT TYPE=“SUBMIT”>

</FORM>

68

Important Note about Important Note about Form ValidationForm 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!

69

CookiesCookies

70

CookiesCookies

• Allow to store persistent data in a text file

• Provide a way to maintain information

between client requests (sessions)

• A cookie is added in the format

name=value;expires=expDate;path=pathValue

• If expires is missing, the cookie lasts for the

current session only (i.e., until you close the

browser)

71

Limitation on CookiesLimitation 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

72

Setting CookiesSetting 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 * 365));

setCookie(“myname”, “myvalue”, exp);

73

Retrieving CookiesRetrieving 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;}

74

Erasing CookiesErasing Cookies

function eraseCookie(name) {var exp = new Date();exp.setTime(exp.getTime() – (1000 * 60 * 60 * 24))setCookie(name, " ", exp)

}