Title: Dynamic HTML (DHTML)
1Dynamic HTML (DHTML)
- Representation and Management of Data on the
Internet
2What 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
3Why 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
4JavaScript ()
- 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
5JavaScript (-)
- What JavaScript cannot do
- No graphics capabilities
- No reading/writing of files on the client side
- No multithreading
6We Will Show
- Getting information on the browser
- Document manipulations
- Content
- Style
- Events handling
- Forms validation
- Using cookies
7Dynamic HTML Object 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
8The 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.
9DOM Example
- ltFORM NAMEmyform ACTIONgt
- Please enter Your age
- ltINPUT TYPETEXT NAMEagegtltBRgt
- and the name of your favorite book
- ltINPUT TYPETEXT NAMEbookgtltBRgt
- lt/FORMgt
- From JavaScript you can get the age input field
as document.myform.age.value
10In Netscape
11all
window
anchors
applets
document
document
body
frames
embeds
document
filters
history
forms
plugins
navigator
images
links
location
plugins
event
scripts
screen
styleSheets
In IE
collections
objects
12Different Browsers
Different browser
Different JavaScript
13A Solution Use JavaScript to Detect the browser
- The document.layers object is specific to
Netscape 4.0, while the document.all object is
specific to IE 4.0
ltSCRIPT LANGUAGE"JavaScript"gt lt!-- ns4
(document.layers)? truefalse ie4
(document.all)? truefalse function init() if
(ns4) doSomethingNetscape() if (ie4)
doSomeThingExplorer() //--gt lt/SCRIPTgt
14Collections 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 loop0 loopltdocument.all.length loop)
- elements ltBRgtdocument.allloop.tagName
15Window Object
16The 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
17Opening and Closing Windows
- 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
18What is the difference between awindow and
window2?
lthtmlgt ltheadgtlttitlegtOpening Windowslt/titlegtlt/headgt
ltbodygt ltformgt ltinput type"button" value"Open
Window" onClick"awindowwindow.open('HelloWorld.
html', 'window2','resizablenowidth200,height2
00')"gt ltPgt ltinput type"button" value"Close
Window" onClick"awindow.close()"gt lt/formgt lta
href"ArrayColors.html" target"window2"gt Load
something else into window2lt/agt lt/bodygt lt/htmlgt
RESULT
19Using 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
20lthtmlgt ltheadgtlttitlegtOnLoad Examplegtlt/titlegt ltscrip
t language"JavaScript"gt var seconds0 function
startTimer() window.setInterval("updateTime()
", 1000) function updateTime() a
document.getElementById("soFar")
soFar.innerTextseconds lt/scriptgtlt/headgt ltbody
onload"startTimer()"gt Seconds that you have
spent looking at this page lta id"soFar"
style"font-weight bold"gt0lt/agt lt/bodygtlt/htmlgt
RESULT
21Window Dialog Boxes
22ltHTMLgt ltHEADgt ltTITLEgtDialogs Examplelt/TITLEgtlt/HEAD
gt ltBODYgt ltFONT SIZE '5'gt ltPgt Hello, this page
will help you to install viruses in your
computer. ltSCRIPT LANGUAGE "JavaScript"gt num
prompt("Enter the number of viruses to install",
10) document.write("You have asked to install "
num " viruses.") lt/SCRIPTgt ltPgtFirst, you
should confirm the installation.ltPgt ltSCRIPT
LANGUAGE "JavaScript"gt 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.") lt/SCRIPTgt lt/FONTgtlt/BODYgtlt/HTMLgt
RESULT
23Status 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
24Information 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
25Location and History
- location
- properties hostname
- methods reload(url), replace(url)
- history (an array of urls)
- properties current, next, previous
- methods go(int)
26lthtmlgt ltheadgt lttitlegtNavigator Propertieslt/titlegt
ltscript language"JavaScript"gt document.write("lth1
gtPropertieslt/h1gt") for (prop in navigator)
document.write(prop " " navigatorprop
"ltbrgt") document.write("lth1gtPropertieslt/h1gt") for
(i0 i lt navigator.plugins.length i)
document.write(navigator.pluginsi.name
"ltbrgt") document.write("lth1gtMime
Typeslt/h1gt") for (i0 i lt navigator.mimeTypes.len
gth i) document.write(navigator.mimeTypesi
.type "ltbrgt") lt/scriptgtlt/headgt ltbodygtlt/bodygt
lt/htmlgt
RESULT
27(No Transcript)
28More System Info
- Some other navigator properties
- navigator.appVersion
- navigator.appName
lthtmlgt ltheadgtlttitlegtNavigator Propertieslt/titlegt lt
script language"JavaScript"gt with (navigator)
document.write("ltpgtAppName",
appName) document.write("ltpgtVersion",
appVersion) lt/scriptgtlt/headgtltbodygtlt/bodygt
lt/htmlgt
RESULT
29Changing the Content of a Page
30Manipulating Objects
- We saw that you can replace text (recall the
timer example) - Here is an expanding list, using this idea
RESULT
31ltHTMLgt ltHEADgtltTITLEgtAn Hello World
Examplelt/TITLEgt ltSCRIPT LANGUAGE
"JavaScript"gt var expanded -1 var
unexpandedText "lta onclick'expand(0)'gtlt/agt
Item 1 of the Menu", " lta onclick'expand(1)'
gtlt/agt Item 2 of the Menu", " lta
onclick'expand(2)'gtlt/agt Item 3 of the
Menu" var expandedText "lta
onclick'expand(0)'gtlt/agt Item 1 of the Menultulgt
" "ltligt SubItem 1 lt/ligt ltligt SubItem 2
lt/ligt lt/ulgt", "lta onclick'expand(1)'gtlt/agt
Item 2 of the Menultulgt " "ltligt SubItem
1b lt/ligtlt/ulgt", "lta onclick'expand(2)'gtlt/agt
Item 3 of the Menultulgt " "ltligt SubItem
2b lt/ligt lt/ulgt"
32function expand(num) if (expanded ! -1)
var a document.getElementById("item"
expanded) a.innerHTML unexpandedTextexpan
ded if (expanded num) expanded -1
else expanded num if (expanded ! -1)
var b document.getElementById("item" num)
b.innerHTML expandedTextnum
lt/SCRIPTgt ltSTYLEgt ul list-style-typenone
a colorred lt/STYLEgt lt/HEADgt
33ltBODYgt ltulgt ltli id "item0"gt lta
onclick"expand(0)"gtlt/agt Item 1 of the Menu
lt/ligt ltli id "item1"gt lta
onclick"expand(1)"gtlt/agt Item 2 of the Menu
lt/ligt ltli id "item2"gt lta
onclick"expand(2)"gtlt/agt Item 3 of the Menu
lt/ligt lt/ulgt lt/BODYgt lt/HTMLgt
RESULT
34Problem
- 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?
35Solution JavaScript Protocol
- You can href to something of the form
javascriptcode - 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
- ltA HREF"javascriptalert('Hello World') return
HelloWorld.html"gtHello Worldlt/Agt - ltA HREFjavascriptvoid(0)gt lt/Agt
- The keyword void makes sure that nothing is
returned
36Solution JavaScript Protocol
- To fix our example add href to
javascriptvoid(0) to each link - Add additional style declarations,
- alink TEXT-DECORATIONnone COLOR red
- avisited TEXT-DECORATIONnone COLOR red
- aactive TEXT-DECORATIONnone COLOR red
- ahover TEXT-DECORATIONnone COLOR red
RESULT
37Manipulating Objects
- You can also replace images in the page
dynamically by setting their source
38ltHTMLgtltHEADgtltTITLEgtImages Examplelt/TITLEgt ltSCRIPT
LANGUAGE "JavaScript"gt pageImages new
Array('dino.gif', 'monkey.gif',
'witch.gif') imgNo 0 function
replaceImage() imgNo (imgNo 1)
pageImages.length document.image.src
pageImagesimgNo lt/SCRIPTgtlt/HEADgt ltBODYgtltFONT
SIZE '5'gt This is a picture ltIMG
SRC"dino.gif" name"image"gtltBRgt ltFORM
NAME"replacePicture"gt ltINPUT TYPE"button"
VALUE"Replace the Picture" onClick"replaceIma
ge()"gt lt/FORMgtlt/FONTgtlt/BODYgtlt/HTMLgt
RESULT
39Changing 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?
40Changing the StyleSheet
- Define the stylesheets in your document
- ltLINK REL"stylesheet" ID HREF"js_oud.css"
DISABLEDgt - ltLINK REL"stylesheet" HREF"js.css"gt
- 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
41Changing the StyleSheet
- function changeCSS(nr)
- if (document.getElementsByTagName)
- x document.getElementsByTagName('link')
- else if (document.all) x document.all.tags('lin
k') - else
- alert('This script does not work in your
browser') - return
-
- nr--
- for (var i0iltx.lengthi)
- dis !(i nr)
- xi.disabled dis
-
RESULT
42Question
- 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)
43Event Model
44Javascript 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
-
45Events 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
- ltTAG eventHandler"JavaScript Code"gt
46ltHEADgtltSCRIPTgtfunction compute(f) Â Â Â if
(confirm("Are you sure?"))Â Â Â Â Â Â f.result.value
eval(f.expr.value)   else      alert("Please
come back again.")lt/SCRIPTgtlt/HEADgtltBODYgtltFORM
gtEnter an expressionltINPUT TYPE"text"
NAME"expr" SIZE15 gtltINPUT TYPE"button"
VALUE"Calculate" onClick"compute(this.form)"gt
ltBRgtResultltINPUT TYPE"text" NAME"result"
SIZE15 gtlt/FORMgtlt/BODYgt
47ltSCRIPT LANGUAGE"JavaScript"gtfunction fun1()
   ...function fun2()    ...lt/SCRIPTgt ltF
ORM NAME"myForm"gtltINPUT TYPE"button"
NAME"myButton"Â Â Â onClick"fun1()"gtlt/FORMgt ltSCRI
PTgtdocument.myForm.myButton.onclickfun2lt/SCRIPT
gt
Resetting the eventHandler
48Event Handlers
onAbort, onBlur, onChange, onClick, onDragDrop,
onError, onFocus, onKeyDown, onKeyPress,
onKeyUp, onLoad, onMouseDown, onMouseMove,
onMouseUp, onMouseOver, onMove, onResize,
onSelect, onSelect, onSubmit, onUnload
49Events Related to DOM Objects
- onUnLoad
- onLoad
- onClick
- onMouseUp
- onMouseDown
- onClick
- onMouseOver
Window events
Button events
Link events
50Event 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
51The Event Object Properties
- 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?
52Type of Event
- function eventType(e)
- if (!e) var e window.event
- alert(e.type)
-
53Target of the Event
- W3C/Netscape target, ExplorersrcElement
- 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) -
54Key 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) -
55Mouse 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) left0, middle1,
right2 Button values (Microsoft) left1
middle4 right2
56Mouse Position
- A complete mess. Combination of the values
- clientX,clientY
- layerX,layerY
- offsetX,offsetY
- pageX,pageY
- screenX,screenY
- x,y
57Order 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 1
Element 2
58Order of Event Handling
- Events are first "captured" from most general to
least general - Events are then "bubbled" from most specific to
least specific
Element 1
Element 2
59Order 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?
60Order 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
-
61lthtmlgt ltheadgt lttitlegtBubble Examplelt/titlegt ltscrip
t language"JavaScript"gt 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() lt/scriptgt lt/headgt
62ltbody onClick"f1()"gt ltp onClick"f2()"gt Bubbling
continues in this paragraphlt/pgt ltp
onClick"f3()"gt Bubbling stops in this
paragraphlt/pgt lt/bodygt lt/htmlgt
RESULT
63Form Validation
64Form 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
65ltscript language"JavaScript"gt 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) lt/scriptgt
66Checking Fields
- function checkform()
- if (document.myform.age.value "")
- alert("You need to specify an age")
- return(false)
- else
- return(true)
-
-
67The Form
- ltFORM METHODGET
- ACTIONmyFormServlet NAMEmyform
- onSubmit"return(checkform())"gt
- AGE ltINPUT TYPETEXT NAMEAgegt
- ltINPUT TYPESUBMITgt
- lt/FORMgt
68Important 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!
69Cookies
70Cookies
- 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
- namevalueexpiresexpDatepathpathValue
- If expires is missing, the cookie lasts for the
current session only (i.e., until you close the
browser)
71Limitation 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
72Setting 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)
73Retrieving Cookies
function getCookie(name) var cname name
var dc document.cookie if (dc.length gt 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
74Erasing Cookies
function eraseCookie(name) var exp new
Date() exp.setTime(exp.getTime() (1000 60
60 24)) setCookie(name, " ", exp)