Download presentation
Presentation is loading. Please wait.
1
1 Representation and Management of Data on the Web Dynamic HTML (DHTML)
2
2 Dynamic HTML HTML CSS Java Script HTML CSS Java Script Simple page Page with Style Dynamic Page (Dynamic HTML)
3
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
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
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
6 JavaScript (-) 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
7
7 We Will Show Forms validation Using cookies Getting information on the browser Document manipulations –Content –Style Events handling
8
8 Document 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
9
9 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[0].text[1].value document.register.email.value
10
10 DOM Example Please enter Your login: and your email: From JavaScript you can get the email input field as: document.register.email.value
11
11 In Netscape
12
12 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
13
13 Different Browsers Different browserDifferent JavaScript Internet Explorer DOM Netscape 4 Dom What Can We Do? Mozilla Dom
14
14 A Solution: Use JavaScript to Detect the Browser Such code may fail because sometimes browsers grant users with the ability to modify the identification strings window.document.write("Navigator: " + navigator.appCodeName); window.document.write(" " + navigator.appName);
15
15 In 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
16
16 Some of the Things You can Do With DOM in Mozilla document.getElementById(id)getElementById document.getElementsByTagNa me(name)getElementsByTagNa me document.createElement(name)createElement parentNode.appendChild(node)appendChild element.innerHTMLinnerHTML element.style.styleAttrstyle element.setAttributesetAttribute element.getAttributegetAttribute element.addEventListeneraddEventListener window._content window.onload window.dump() window.scrollTo()
17
17 Form Validation
18
18 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 fields If values are illegal, you can prevent the form information from being sent
19
19 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); } Get the form as a parameter and validate it
20
20 Checking Fields function validateLogin() { if (document.register.login.value == "") { alert("You need to insert your login"); return(false); } else { return(true); } Does not have to get the form as a parameter
21
21 Checking Fields function validateEmail() { at=document.register.email.value.indexOf("@") if (at == -1) { alert("Not a valid e-mail") return false } function checkForm() { return (validateLogin() && validateEmail()); }
22
22 The Form <FORM METHOD=‘GET’ ACTION=‘myServlet’ NAME=‘register onSubmit="return(checkForm())"> Login: Email:
23
23 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!
24
24 Cookies
25
25 Cookies 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)
26
26 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 Depends of the browser
27
27 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; }
28
28 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);
29
29 Window Object
30
30 The 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
31
31 Opening 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
32
32 Opening Windows <input type="button" value="Open Window" onClick=“awindow=window.open('HelloWorld.html', 'window2','resizable=no,width=200,height=200')"> <input type="button" value="Close Window" onClick="awindow.close()"> Load something else into window2 What is the difference between awindow and window2?
33
33 The widows are resizable!
34
34 Window Dialog Boxes alert: confirm: returns true or false prompt: returns value entered or null if no value was entered
35
35 Dialogs Example Hello, this page will help you to install viruses in your computer. num = prompt("Enter the number of viruses to install", 10); document.write("You have asked to install " + num + " viruses."); First, you should confirm the installation. 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.") }
36
36
37
37 Status Bar change window.status to change the status bar value change window.defaultStatus to change the default value of the status bar
38
38 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
39
39 Location and History location: –properties: hostname –methods: reload(url), replace(url) history: (an array of urls) –properties: current, next, previous –methods: go(int)
40
40 Navigator Properties document.write(" Properties ") 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 + " ")
41
41
42
42 Changing the Content of a Page
43
43 Manipulating 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
44
44 function changeText() { p = document.getElementById("pid"); p.style.color = "blue“; p.style.fontSize = "18pt" } link to W3C Example 1
45
45 Example 2
46
46 An Hello World Example var expanded = -1 var unexpandedText=[ " + Item 1 of the Menu", " + Item 2 of the Menu", " + Item 3 of the Menu"] var expandedText=[ " = Item 1 of the Menu " + " SubItem 1 SubItem 2 ", " = Item 2 of the Menu " + " SubItem 1b ", " = Item 3 of the Menu " + " SubItem 2b "] Example 2
47
47 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] } ul {list-style-type:none} a {color:red}
48
48 + Item 1 of the Menu + Item 2 of the Menu + Item 3 of the Menu
49
49 Problem 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 element must be a link. Where to?
50
50 Solution: JavaScript Protocol 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: – Hello World – … The keyword void makes sure that nothing is returned
51
51 Solution: JavaScript Protocol 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}
52
52 Manipulating Objects You can also replace images in the page dynamically by setting their source
53
53 Images Example pageImages = new Array('dino.gif', 'monkey.gif', 'witch.gif'); imgNo = 0 ; function replaceImage() { imgNo = (imgNo + 1) % pageImages.length; document.image.src = pageImages[imgNo]; } This is a picture: <INPUT TYPE="button" VALUE="Replace the Picture" onClick="replaceImage()">
54
54 Changing 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?
55
55 Changing the StyleSheet Define the stylesheets in your document: – 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;
56
56 Changing the StyleSheet function 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; }
57
57 Question 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)
58
58 Event Model
59
59 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 –…–…
60
60 Events 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- >document->p->a 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
61
61 Are 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?)
62
62 In Mozilla The event starts at the root, goes down to the leaf and then goes up again to the root window->document->p->a->p->document->window Event capture – catching the event while it moves down the tree Event bubbling – the event goes up in the tree If you don’t care when to handle the event you can set an event handler: element.onEventType = functionName
63
63 Setting 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
64
64 function compute(f) { if (confirm("Are you sure?")) f.result.value = eval(f.expr.value) else alert("Please come back again.") } Enter an expression: <INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)"> Result:
65
65 function fun1() {... } function fun2() {... } document.myForm.myButton.onclick=fun2 Resetting the eventHandler
66
66 Event Handlers onAbort, onBlur, onChange, onClick, onDragDrop, onError, onFocus, onKeyDown, onKeyPress, onKeyUp, onLoad, onMouseDown, onMouseMove, onMouseUp, onMouseOver, onMove, onResize, onSelect, onSelect, onSubmit, onUnload
67
67 Events Related to DOM Objects onUnLoad onLoad onClick onMouseUp onMouseDown onClick onMouseOver Window events Button events Link events
68
68 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
69
69 Getting 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
70
70 Order 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
71
71 Order 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
72
72 Order 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?
73
73 Order 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 }
74
74 Bubble Example 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(); }
75
75 Bubbling continues in this paragraph Bubbling stops in this paragraph
76
76 Event 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
77
77 Event Handling in DOM addEventListener – allows the registration of event listeners on the event targetaddEventListener dispatchEvent – allows the dispatch of events into the implementation's event modeldispatchEvent removeEventListener – allows the removal of event listeners from the event targetremoveEventListener
78
78 addEventListener 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)
79
79 DOM Event Examples #t { border: 1px solid red } #t1 { background-color: pink; } // 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); } one two Example
80
80
81
81 The 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?target –Which key was pressed during the event?key –Which mouse button was pressed during the event?mouse button –What was the mouse position during the event?mouse position
82
82 Mouse 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
83
83 Invocations Three types of invocation: –Immediate –Deferred –Hybrid
84
84 Immediate Invocation Immediate invocation of JavaScript document.write(" This page was updated on " + document.lastModified + ". ") Code is interpreted and immediately executed
85
85 Deferred Invocation function showDate() { document.write(" This page was updated on " + document.lastModified + ". ") } Deferred invocation of JavaScript Code is executed when the function is called (upon event)
86
86 Invocation Example document.writeln(" Script at the head of the Document "); function p1() { window.confirm(“At p1()"); } function p2() { document.writeln(" At function p2 "); } Invocations Example 1
87
87 Some Text in the document body document.writeln(" At a script in the body "); p2(); After the script in the body. 6 2 3 4 5
88
88 In form validation, should we use immediate or deferred invocation?
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.