Download presentation
Presentation is loading. Please wait.
1
JavaScript JavaScript and HTML Text Chapter 4
2
Client-side JavaScript Defines a collection of objects, methods and properties that allow scripts to interact with XHTML. This chapter covers DOM, although an understanding of DOM is not necessary to use client-side JavaScript. It covers techniques for accessing document elements, and the basics of events and event-handling.
3
DOM The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. [1] Objects in the DOM tree may be addressed and manipulated by using methods on the objects. The public interface of a DOM is specified in its application programming interface (API). The history of the Document Object Model is intertwined with the history of the "browser wars" of the late 1990s between Netscape Navigator and Microsoft Internet Explorer, as well as with that of JavaScript and JScript, the first scripting languages to be widely implemented in the layout engines of web browsers. languageHTMLXHTMLXML [1] application programming interfacebrowser warsNetscape Navigator Microsoft Internet ExplorerJavaScript JScriptscripting languages
4
The execution environment A browser displays an XHTML document in a window on the computer screen. This is the JavaScript Window object. All variables in your script are properties of some object. The Window’s properties are visible to all scripts in the displayed document, (this includes global variables). There can be multiple Window objects. The Document object is the displayed HTML document. It is a property (the document property) of a Window object. The Document object has a Forms array. Each Forms array element has an elements array as a property. The Document object also has a property arrays for anchors, links, images and applets.
5
Hierarchy Window Object Document property Forms Array A Form in the array Elements array Another form…etc Other window properties
6
DOM: Document Object Model Under development since mid-90s. Currently DOM 3 is the latest version DOM1 focused on the XHTML and XML document model. DOM 2 includes document traversal and an event model.
7
Values indicate the level of support in the most recent version of the layout engine, or (if a version number is given) in the specified version. ValueMeaning Yes Indicates that the layout engine fully supports this property/element when valid values are used. No Indicates that the property/element is completely ignored. Partial Indicates that the property/element is understood, but that not all values are supported. Supported values are implemented correctly. Incorrect Indicates that the property/element is understood, but that it is not implemented correctly in all cases. Experimental Indicates that the property/element is understood, but supported under an alternate name. May be incomplete or buggy. Dropped Indicates that the property/element is no longer supported. Nightly build Indicates that the property/element is supported to some extent in an experimental/nightly build. Future support is expected. Depends Indicates that the property/element is supported only on certain platforms, or if certain settings are configured.
8
DOM compliance by layout engines Trident Tasma n GeckoWebKitKHTMLPresto DOM16.0Yes1.085Yes1.0 DOM2MostlyPartialMostlyPartialMostly DOM3No Partial
9
The document object onLoad event handler // The onload event handler function load_greeting () { alert("You are visiting the home page of \n" + "Pete's Pickled Peppers \n" + "WELCOME!!!"); } Some text
10
The previous html rendered
11
The document object document head body title script function Some text
12
DOM support in JavaScript Elements of XHTML are objects in JavaScript, their attributes are object properties. Example, type and name are properties of the input object
13
Accessing objects and properties Addresses are needed to access objects and properties of the document from within a script. The address is referred to as the object’s DOM address.
14
Text example <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> address example
15
Address of the button is…? Using the DOM address, the button is document.forms[0].elements[0] Using element names, the address of the button is document.myForm.turniton A validation issue: the XHTML 1.1 standard does not allow the use of the name attribute for a form, though the browser has no trouble with it. You can also use a JavaScript method, getElementById(“…”) as in document. getElementById(“turniton”) Any expression that evaluates to string can serve as the parameter to getElementById
16
Names and ids Names are needed for form-processing and ids are handy for DOM addressing so often both are used. Buttons in a group of radiobuttons always have the same name. Buttons in a group of checkboxes may have the same name. In such cases, the names cannot be used in the DOM address. They may have an id though. Implicit arrays are associated with button groups, and these provide an alternative to using names or ids for these addresses. (See course ppt example).
17
Table 5.2 excerpt: Text shows event attributes and their tags AttributeTagdescription onblur Link loses input focus Button loses input focus onchange Input element is changed and loses input focus onclick Link acquires input focus
18
How to register the event handler with DOM 0 event model Assign the event handler script to an event tag attribute, eg., If the handler is more than one statement, use a function, as in,
19
Body elements load and unload are the two most common body-element events. See text example load greeting in previous slide
20
Buttons Buttons are a good way to get input from a browser. click is the most common button event Example from previous slide shows how to register an event to handle button-click:
21
Buttons Another way to do it would be to assign the handler to the associated event property on the button: document.getElementById(“somebutton”).onclick= myButtonHandler;
22
Rb example: form in body <input type = "radio" name = "planeButton" onclick = "planeChoice(152)" /> Model 152 <input type = "radio" name = "planeButton" onclick = "planeChoice(172)" /> Model 172 (Skyhawk) <input type = "radio" name = "planeButton" onclick = "planeChoice(182)" /> Model 182 (Skylane) <input type = "radio" name = "planeButton" onclick = "planeChoice(210)" /> Model 210 (Centurian)
23
Slightly modified Radiobutton click event handler function planeChoice (plane) { var plane; var s; switch (plane) { case 152: s="A small two-place-airplane for flight training"; break; case 172: s="The smaller of two four-place airplanes"; break; case 182: s="The larger of two four-place airplanes"; break; case 210: s="A six-place high-performance airplane"; break; default: s="Error in JavaScript function planeChoice"; } alert(s);}
24
The form
25
Alert from rb click
26
Different version of this rb example Cessna single-engine airplane descriptions Model 152 Model 172 (Skyhawk) Model 182 (Skylane) Model 210 (Centurian) var dom = document.getElementById("myForm"); dom.elements[0].onclick = planeChoice; dom.elements[1].onclick = planeChoice; dom.elements[2].onclick = planeChoice; dom.elements[3].onclick = planeChoice;
27
Different version of the same from text function planeChoice (plane) { var dom = document.getElementById("myForm"); for (var index = 0; index < dom.planeButton.length; index++) { if (dom.planeButton[index].checked) { plane = dom.planeButton[index].value; break; } } switch (plane) { case "152": alert("A small two-place airplane for flight training"); break; case "172": alert("The smaller of two four-place airplanes"); break; case "182": alert("The larger of two four-place airplanes"); break; case "210": alert("A six-place high-performance airplane"); break; default:: alert("Error in JavaScript function planeChoice"); break; } }
28
Text box events Textbox creates four events: blur, focus, change, select.
29
An example from the text Text example (pg 207 nochange.html and nochange.js) I saved this in …\Higgindm\source\chapt5\coffee.html and coffee.js
30
The Compute cost function function computeCost() { var french = document.getElementById("french").value; var hazlenut = document.getElementById("hazlenut").value; var columbian = document.getElementById("columbian").value; // Compute the cost document.getElementById("cost").value = totalCost = french * 3.49 + hazlenut * 3.95 + columbian * 4.59; } //* end of computeCost
31
A piece of the table to create the form Product Name Price Quantity French Vanilla (1 lb.) $3.49 <input type = "text" id = "french" size ="2" />
32
computation of the total cost <input type = "button" value = "Total Cost" onclick = "computeCost();" /> <input type = "text" size = "5" id = "cost" onfocus = "this.blur();" />
33
Ordering coffee: user can’t alter any cost or price textbox
34
Validating form input Format, completeness (including datatypes, etc) is commonly done in JavaScript, shifting this work off the server. Besides the fact that the client usually has a lighter load, doing this data entry checking on the client saves network traffic. An alert indicating the error, putting the field in focus, and selecting the contents would be appropriate actions. The focus() method and select() methods on the DOM element would effect the latter two actions.
35
IE6 vs Moz7 In IE6 focus and select only work if the handler is registered by assigning an event property. In Moz7 select works ok but focus does not.
36
Return value of data checking handler A handler checking form data should return false to keep the (bad) form data from being sent on to the server.Return true if the data is ok. The text provides an example: the user enters a password, then enters it again. We need to check that the pw was entered into the first field (it is not the empty string) and that the contents of the first pw field match the second pw field. If all is well the checker returns true. Otherwise it returns to the first pw field. The checker is called on submit, or when the second textbox loses focus, the onblur event.
37
Entering two different pws in mozilla
38
After clicking ok in the alert in IE: note focus
39
Function to check pws function chkPasswords() { var init = document.getElementById("initial"); var sec = document.getElementById("second"); if (init.value == "") { alert("You did not enter a password \n" + "Please enter one now"); init.focus(); return false; } if (init.value != sec.value) { alert("The two passwords you entered are not the same \n" + "Please re-enter both now"); init.focus(); init.select(); return false; } else return true;}
40
Body & form Password Input Your password Verify password <!-- // Set submit button onsubmit property to the event handler document.forms[0].onsubmit = chkPasswords; // -->
41
Validator example in text Check a name and phone number for format errors.
42
Input validation: check name
43
Checking input: phone number
44
This input was accepted…. Is it ok?
45
Check name function chkName() { var myName = document.getElementById("custName"); // Test the format of the input name // Allow the spaces after the commas to be optional // Allow the period after the initial to be optional var pos = myName.value.search(/\w+, ?\w+, ?\w.?/); if (pos != 0) { alert("The name you entered (" + myName.value + ") is not in the correct form. \n" + "The correct form is: " + "last-name, first-name, middle-initial \n" + "Please go back and fix your name"); myName.focus(); myName.select(); return false; } else return true; }
46
Check number function chkPhone() { var myPhone = document.getElementById("phone"); // Test the format of the input phone number var pos = myPhone.value.search(/^\d{3}-\d{3}-\d{4}$/); if (pos != 0) { alert("The phone number you entered (" + myPhone.value + ") is not in the correct form. \n" + "The correct form is: ddd-ddd-dddd \n" + "Please go back and fix your phone number"); myPhone.focus(); myPhone.select(); return false; } else return true; }
47
Form and script Name (last name, first name, middle initial) Phone number (ddd-ddd-dddd) <!-- // Set form element object properties to their // corresponding event handler functions document.getElementById("custName").onchange = chkName; document.getElementById("phone").onchange = chkPhone; // -->
48
Validator2 from text Uses the DOM2 model. Documents can mix the Dom0 and DOM2 models. But DOM2 is not a superset of DOM0 and doesn’t support its model.
49
the DOM2 model ModuleEvent interfaceEvent types HTMLEventsEventabort, blur, change, error, focus, load,… MouseEventsMouseEventclick,mousedown, mousemove, mouseup, mouseover,…
50
DOM2 event-handling much more complicated than DOM0: There are 3 phases: capture, target node execution, and bubbling In capture, the event object propagates down from the root to the target node looking for an enabled event-handler. When the event reaches the target node, any registered handler there are executed. In bubbling, the event travels back to the root executing enabled event-handlers for this event.
51
bubbling Not every event bubbles. load and unload events do not bubble. Mouseevents do bubble. Any handler can stop further propagation using the stopPropagation method of the event. Bubbling came from exceptionhandling. Exceptions in C++ and Java can be thrown and caught, so to avoid redundancy a single handler might deal with all events of a certain type.
52
DOM0 vs DOM2 more… DOM0 validating methods return false to prevent sending a form to a server. DOM2 has a method preventDefault which serves the same purpose. We saw how to register a method to handle an event in DOM0. In DOM2 it is effected by using the addEventListener method.
53
DOM0 vs DOM2 more… addEventListener takes 3 parameters, the name of the event as a string literal (eg., “mouseup”), the handler function specified as code or a function name, and finally a boolean indicates if the function is enabled for the capture phase. If not, it may be called at the target node or during bubbling. removeEventListener – a method which takes the same 3 parameters as addEventListener – makes it possible to remove an event handler.
54
DOM0, Moz7 and DOM2 DOM0 and Moz7 treat the keyword this in an event handler as a reference to the target node. This is not required in DOM2 and other browsers may not support it so use of this in a handler may be non-portable. The alternative is to use the currentTarget property of Event which always references the object on which the handler is being executed.
55
Mouse MouseEvent inherits from Event interface. It adds several properties, most useful of which are clientX and clientY, the x and y coordinates of the mouse event in the browser window, measured from upper LH corner of the document in the browser window (not the upper left of the display).
56
Redo of validator in text function chkName(event) { // Get the target node of the event var myName = event.currentTarget; var pos = myName.value.search(/\w+, ?\w+, ?\w.?/); if (pos != 0) { alert("The name you entered (" + myName.value + ") is not in the correct form. \n" + "The correct form is: " + "last-name, first-name, middle-initial \n" + "Please go back and fix your name"); myName.focus(); myName.select(); }
57
validator2 in text function chkPhone(event) { // Get the target node of the event var myPhone = event.currentTarget; // Test the format of the input phone number var pos = myPhone.value.search(/^\d{3}-\d{3}-\d{4}$/); if (pos != 0) { alert("The phone number you entered (" + myPhone.value + ") is not in the correct form. \n" + "The correct form is: ddd-ddd-dddd \n" + "Please go back and fix your phone number"); myPhone.focus(); myPhone.select(); }
58
Body & form Customer Information Name (last name, first name, middle initial) Phone number (ddd-ddd-dddd) <!-- /* Get the DOM addresses of the elements and register the event handlers */ var customerNode = document.getElementById("custName"); var phoneNode = document.getElementById("phone"); customerNode.addEventListener("change", chkName, false); phoneNode.addEventListener("change", chkPhone, false); // -->
59
You can get the browser name appName of navigator returns the browser.
60
Navigate.html in text Using navigator <!-- // The event handler function to display the browser name // and its version number function navProperties() { alert("The browser is: " + navigator.appName + "\n" + "The version number is: " + navigator.appVersion + "\n");} // -->
61
Mouse click coordinates Drag and drop <!-- function mouseFunction(event) { var posX = event.clientX; var posY = event.clientY; alert("position x="+ posX+ " y="+posY); event.stopPropagation(); event.preventDefault(); } //** end of grabber // --> <img id = "Patricia" src = "Patricia.jpg" alt = "(Picture of Patricia)" onmousedown = "mouseFunction(event);"/>
62
Picture comes up
63
On mousedown alert
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.