Title: Representation and Management of Data on the Web
1Dynamic HTML (DHTML)
- Representation and Management of Data on the Web
2Dynamic HTML
Java Script
Java Script
HTML
CSS
HTML
HTML
CSS
HTML
Simple page
Page with Style
Dynamic Page (Dynamic HTML)
3What 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
4Why 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
5JavaScript ()
- 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
6JavaScript (-)
- What JavaScript cannot do
- No graphics capabilities (i.e., graphics is
limited to what HTML and CSS can do) - No reading/writing of files on the client side
- No multithreading
7We Will Show
- Forms validation
- Using cookies
- Getting information on the browser
- Document manipulations
- Content
- Style
- Events handling
8Document 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
9The 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.
10DOM Example
- ltFORM NAMEregister ACTIONgt
- Please enter Your login
- ltINPUT TYPETEXT NAMElogingtltBRgt
- and your email
- ltINPUT TYPETEXT NAMEemailgtltBRgt
- lt/FORMgt
- From JavaScript you can get the email input field
as document.register.email.value
11In Netscape
12all
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
13Different Browsers
Different browser
Different JavaScript
?
?
Internet Explorer DOM
Netscape 4 Dom
Mozilla Dom
What Can We Do?
14A Solution Use JavaScript to Detect the Browser
ltSCRIPT LANGUAGE"JavaScript"gt window.document.wr
ite("Navigator " navigator.appCodeName) w
indow.document.write(" " navigator.appName)
lt/SCRIPTgt
- Such code may fail because sometimes browsers
grant users with the ability to modify the
identification strings
15In Mozilla
- Mozilla uses the W3C DOM standard
- The API resembles the XML DOM API that we have
studied - The user can access and manipulate
- document, element, nodeList, attribute,
namedNodeMap
16Some of the Things You can Do With DOM in Mozilla
- document.getElementById(id)
- document.getElementsByTagName(name)
- document.createElement(name)
- parentNode.appendChild(node)
- element.innerHTML
- element.style.styleAttr
- element.setAttribute
- element.getAttribute
- element.addEventListener
- window._content
- window.onload
- window.dump()
- window.scrollTo()
17Form Validation
18Form 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
19ltscript 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
Get the form as a parameter and validate it
20Checking Fields
- function validateLogin()
- if (document.register.login.value "")
- alert("You need to insert your login")
- return(false)
- else
- return(true)
-
-
21Checking Fields
- function validateEmail()
- atdocument.register.email.value.indexOf("_at_")
- if (at -1)
- alert("Not a valid e-mail")
- return false
-
-
- function checkForm()
- return (validateLogin() validateEmail())
22The Form
- ltFORM METHODGET
- ACTIONmyServlet NAMEregister
- onSubmit"return(checkForm())"gt
- Login ltINPUT TYPETEXT NAMElogingt
- Email ltINPUT TYPETEXT NAMEemailgt
- ltINPUT TYPESUBMITgt
- lt/FORMgt
23Important 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!
24Cookies
25Cookies
- 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)
26Limitation 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
Depends of the browser
27Retrieving 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
28Setting 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)
29Window Object
30The 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
31Opening 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
32lthtmlgt ltheadgtlttitlegtOpening Windowslt/titlegtlt/headgt
ltbodygt ltformgt ltinput type"button" value"Open
Window" onClickawindowwindow.open('HelloWorld.
html', 'window2','resizableno,width200,height2
00')"gt ltPgt ltinput type"button" value"Close
Window" onClick"awindow.close()"gt lt/formgt lta
hrefhttp//www.cs.huji.ac.il"
target"window2"gt Load something else into
window2lt/agt lt/bodygt lt/htmlgt
What is the difference between awindow and
window2?
33The widows are resizable!
34Window Dialog Boxes
35ltHTMLgt 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
36(No Transcript)
37Status Bar
- change window.status to change the status bar
value - change window.defaultStatus to change the default
value of the status bar
38Information 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
39Location and History
- location
- properties hostname
- methods reload(url), replace(url)
- history (an array of urls)
- properties current, next, previous
- methods go(int)
40lthtmlgt ltheadgt lttitlegtNavigator Propertieslt/titlegt
ltscript language"JavaScript"gt document.write("lth1
gtPropertieslt/h1gt") for (prop in navigator)
document.write(prop " " navigatorprop
"ltbrgt") document.write("lth1gtPluginslt/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
41(No Transcript)
42Changing the Content of a Page
43Manipulating Objects
- We can replace text and style of elements and
thus manipulate them - Two examples are given
- The second example is an expanding list, using
this idea
44Example 1
- lthtmlgt ltheadgt ltscriptgt
- function changeText()
- p document.getElementById("pid")
- p.style.color "blue
- p.style.fontSize "18pt"
-
- lt/scriptgt lt/headgt ltbodygt
- ltp idpid onclickwindow.location'http//www.w
3c.org'gtlink to W3Clt/pgt - ltformgt ltinput value"rec" type"button"
onclick"changeText()" /gt - lt/formgt lt/bodygt lt/htmlgt
45Example 2
46ltHTMLgt 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"
Example 2
47function 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
48ltBODYgt 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
49Problem
- In the previous example, when the mouse was over
the and , the mouse was not a hand (i.e.,
they were not treated as links) - To make the normal hand, the ltagt element must be
a link. Where to?
50Solution 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
51Solution 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
52Manipulating Objects
- You can also replace images in the page
dynamically by setting their source
53ltHTMLgtltHEADgtltTITLEgtImages 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
54Changing 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?
55Changing 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
56Changing 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
-
57Question
- 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)
58Event Model
59Javascript 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
-
60Events in a DOM Tree
- Events occur on leafs in the DOM tree
- For example, consider a link inside a paragraph
inside a document inside a window
window-gtdocument-gtp-gta - A mouse click on the link is also a click on all
the elements that are above the link in the DOM
tree - The leaf on which the event occurred is called
the target of the event
61Are Events Going Up or Down in the DOM Tree?
- When an event occurs on a web document, such as
when one clicks on a link, a special object,
called an event object, is created - When an event occurs, it travels through the
document, cascading through the elements in the
page until it can travel no more - In Netscape, events will travel inward towards
the target of the event (what is the problem with
this?) - In Internet Explorer, events travel outward
towards the browser window (what is the problem
with this?)
62In Mozilla
- The event starts at the root, goes down to the
leaf and then goes up again to the root - window-gtdocument-gtp-gta-gtp-gtdocument-gtwindow
- Event capture catching the event while it moves
down the tree - Event bubbling the event goes up in the tree
- If you dont care when to handle the event you
can set an event handler - element.onEventType functionName
63Setting Events on TAGS
- If an event applies to an HTML tag, then you can
directly 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
64ltHEADgtltSCRIPTgtfunction 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
65ltSCRIPT 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
66Event Handlers
onAbort, onBlur, onChange, onClick, onDragDrop,
onError, onFocus, onKeyDown, onKeyPress,
onKeyUp, onLoad, onMouseDown, onMouseMove,
onMouseUp, onMouseOver, onMove, onResize,
onSelect, onSelect, onSubmit, onUnload
67Events Related to DOM Objects
- onUnLoad
- onLoad
- onClick
- onMouseUp
- onMouseDown
- onClick
- onMouseOver
Window events
Button events
Link events
68Event 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
69Getting the Event Object
- In Mozilla and Netscape, 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 - In Explorer, an event can be achieved by
window.event
70Order 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
71Order 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
72Order of Event Handling
- Registering event handlers for capturing phase
requires using an eventListener - 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?
73Order 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
-
74lthtmlgt 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
75ltbody 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
76Event Capturing
- Events are falling down the DOM tree and then
bubbling up - The following two demands require an event
listener - Needing two or more handlers that listen to the
same event on the same object - Applying the handler only during the capture
phase or only during the bubbling phase
77Event Handling in DOM
- addEventListener allows the registration of
event listeners on the event target - dispatchEvent allows the dispatch of events
into the implementation's event model - removeEventListener allows the removal of event
listeners from the event target
78addEventListener
- element.addEventListener( type, listener,
useCapture ) - type the type of the event
- listener the method to be called
- useCapture If capture is true, the function is
executed when the event is in capture phase
(traveling towards it's target). If capture is
false, it's executed when the event is in
bubbling phase (traveling back up to the browser
window)
79Example
lthtmlgt ltheadgt lttitlegtDOM Event Exampleslt/titlegt
ltstylegt t border 1px solid red t1
background-color pink lt/stylegt ltscriptgt
// Event Registration Example function l_func()
t2 document.getElementById("t2")
t2.innerHTML "three"
function load() el document.getElementById(
"t") el.addEventListener("click", l_func,
false) lt/scriptgt lt/headgt ltbody
onload"load()"gt lttable id"t"gt lttrgtlttd
id"t1"gtonelt/tdgtlt/trgt lttrgtlttd
id"t2"gttwolt/tdgtlt/trgt lt/tablegt lt/bodygt lt/htmlgt
80(No Transcript)
81The 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?
82Mouse Position
- A complete mess. Combination of the values
- clientX,clientY
- layerX,layerY
- offsetX,offsetY
- pageX,pageY
- screenX,screenY
- x,y
83Invocations
- Three types of invocation
- Immediate
- Deferred
- Hybrid
84Immediate Invocation
- lthtmlgt
- ltbodygt
- lth1gtImmediate invocation of JavaScriptlt/h1gt
- ltscript language"JavaScript"gt
- document.write("lthrgtltpgtThis page was updated on "
document.lastModified ".lt/pgt") - lt/scriptgt
- lt/bodygt
- lt/htmlgt
Code is interpreted and immediately executed
85Deferred Invocation
- lthtmlgtltheadgt
- ltscript language"JavaScript"gt
- function showDate()
- document.write("lthrgtltpgtThis page was updated on
" document.lastModified ".lt/pgt") -
- lt/scriptgt
- lt/headgtltbodygt
- lth1gtDeferred invocation of JavaScriptlt/h1gt
- ltformgtltinput type"button" name"test"
value"showDate" onClick"showDate()"gtlt/formgt - lt/bodygtlt/htmlgt
Code is executed when the function is called
(upon event)
86- ltHTMLgt
- ltHEADgtltTITLEgtInvocation Examplelt/TITLEgt
- ltSCRIPT LANGUAGE "JavaScript"gt
- document.writeln("ltFONT SIZE '5' COLOR
'blue'gt - Script at the head of the Documentlt/FONTgt")
-
- function p1()
- window.confirm(At p1()")
-
- function p2()
- document.writeln("ltFONT SIZE '5' COLOR
red'gt - At function p2lt/FONTgt")
-
- lt/SCRIPTgt
- lt/HEADgt
1
Invocations Example
876
- ltBODY onLoad "p1()"gt
- ltFONT SIZE '5 COLORmagentagt
- ltP ID "paragraphText"gt
- Some Text in the document body
- lt/Pgt
- lt/FONTgt
- ltSCRIPT LANGUAGE "JavaScript"gt
- document.writeln("ltFONT SIZE '5' COLOR
purple'gt At a script in the bodylt/FONTgt") - p2()
- lt/SCRIPTgt
- ltPgt
- ltBIGgtAfter the script in the body.lt/BIGgt
- lt/BODYgt
- lt/HTMLgt
2
3
4
5
88In form validation, should we use immediate or
deferred invocation?