Archive for September, 2007

192Part IIIDocument Objects ReferenceUnfortunately, neither IE5 through IE6 (Web server setup)

Sunday, September 30th, 2007

192Part IIIDocument Objects ReferenceUnfortunately, neither IE5 through IE6 on Windows nor IE5 for Macintosh implements theW3C DOM event model. You can, however, make the two event models work together if youassign event handlers by way of object properties or tag attributes, and throw in a littleobject detection described later in this chapter and in more detail in Chapter 25. Mixing Object ModelsThe more browsers that your audience uses, the more likely you will want to make your pageswork on as many browsers as possible. You ve seen in this chapter that scripts written for olderbrowsers, such as Navigator 2 and Internet Explorer 3, tend to work in even the latest browserswithout modification. But aiming at that compatibility target doesn t let you take advantage ofmore advanced features, in particular Dynamic HTML. You must balance the effort required tosupport as many as four classifications of browsers (non-DHTML, NN4, IE4/5, and W3C DOMcommon denominator in IE6 and Moz1) against the requirements of your audience. Moreover, those requirements can easily change over time. For example, the share of the audience usingnon-DHTML and NN4 browsers will diminish over time, while the installed base of browserscapable of using the Microsoft IE DOM (for IE4+) and the W3C DOM (IE6+ and Moz1+) willincrease. If the percentage of visitors using NN4 is not significant at this point, you may welldecide to not worry about implementing DHTML features for that browser and lump NN4together with the rest of the non-DHTML browsers. For any given application or Web site, it is important to develop a strategy to apply to thedeployment of scripted features. But be aware that one strategy simply cannot fit all situa- tions. The primary considerations are the breadth of browser versions reaching your site(many for public sites; perhaps only one for a tightly controlled intranet) and the amount ofDHTML you intend to implement. In the rest of this section, you see three scenarios and strategies employed to meet the devel- oper s requirements. Although they are labeled as three different levels of aggressiveness, itis likely that you can apply individual techniques from each of the levels in establishing astrategy of your own. The conservative approachIn the first scenario, the content requires a modest level of data entry interaction with a uservia a form as well as image rollovers. Supported browsers encompass the entire range of non- scriptable and scriptable browsers, with one version of each page to serve all visitors. If the form gathers information from the user for submission to a server CGI that stores thedata in a database or performs a search based on user-supplied criteria, the obvious modeof entry is through traditional form control elements. Scriptable browsers can perform pre- submission validations to hasten the correction of any improperly formatted fields. Eventhandlers attached to the text fields (onchangeevent handlers) and an onsubmitevent han- dler for the form itself can do the validation on the client. Nonscriptable browsers ignore theevent handlers, and the form is submitted as usual, relying on server-side validation of inputdata (and the slow back-and-forth processing that this entails when there is an error or miss- ing field data). For image rollovers, links surround the image elements. The onmouseoverand onmouseoutevent handlers for the links trigger functions that swap images. By wrapping the statementsin the event handler functions in ifconstructions that test for the presence of the document.imagesarray, first-generation scriptable browsers that don t implement images as objectsperform no action:

Photography web hosting - 191Chapter 14Document Object Model EssentialsThe W3C event model

Saturday, September 29th, 2007

191Chapter 14Document Object Model EssentialsThe W3C event model also introduces a new concept called the event listener. An event lis- tener is essentially a mechanism that instructs an object to respond to a particular kind ofevent very much like the way the event handler attributes of HTML tags respond to events. But the DOM recommendation points out that it prefers use of a more script-oriented way ofassigning event listeners: the addEventListener()method available for every node in thedocument hierarchy. Through this method, you advise the browser whether to force an eventto bubble up the hierarchy (the default behavior that is also in effect if you use the HTMLattribute type of event handler) or to be captured at a higher level. Functions invoked by the event listener receive a single parameter consisting of the eventobject whose properties contain contextual details about the event (details such as the posi- tion of a mouse click, character code of a keyboard key, or a reference to the target object). For example, if a form includes a button whose job is to invoke a calculation function, theW3C DOM prefers the following way of assigning the event handler: document.getElementById( calcButton ).addEventListener( click , doCalc, false); The addEventListener()method takes three parameters. The first parameter is a string ofthe event to listen for; the second is a reference to the function to be invoked when that eventfires; and the third parameter is a Boolean value. When you set this Boolean value to true, itturns on event capture whenever this event is directed to this target. The function then takesits cue from the event object passed as the parameter: function doCalc(evt) { // get shortcut reference to input button s formvar form = evt.target.form; var results = 0; // other statements to do the calculation// form.result.value = results; } To modify an event listener, you use the removeEventListener()method to get rid of theold listener and then employ addEventListener()with different parameters to assign thenew one. Preventing an event from performing its default action is also a different procedure in theW3C event model than in IE. In IE4 (as well as NN3 and NN4), you can cancel the defaultaction by allowing the event handler to evaluate to return false. While this still works inIE5+, Microsoft includes another property of the window.eventobject, called returnValue. Setting that property to falseanywhere in the function invoked by the event handler alsokills the event before it does its normal job. But the W3C event model uses a method of theevent object, preventDefault(), to keep the event from its normal task. You can invoke thismethod anywhere in the function that executes when the event fires. Detailed information about an event is contained in an event object that must be passed to anevent handler function where details may be read. If you assign event handlers via the W3CDOM addEventListener()method or an event handler property, the event object is passedautomatically as the sole parameter to the event handler function. Include a parameter vari- able to catch the incoming parameter: function swap(evt) { // statements here to work with W3C DOM event object} But if you assign events via a tag attribute, then you must explicitly pass the event object inthe call to the function:

Web hosting bandwidth - 190Part IIIDocument Objects Referenceobject.prototype.__defineSetter__( propName , function([param1[,…[,paramN]]]) { // statementsreturn

Saturday, September 29th, 2007

190Part IIIDocument Objects Referenceobject.prototype.__defineSetter__( propName , function([param1[,…[,paramN]]]) { // statementsreturn returnValue; }) The example in Listing 14-3 demonstrates how to add a read-only property to every HTMLelement object in the current document. The property, called childNodeDetail, returns anobject; the object has two properties, one for the number of element child nodes and one forthe number of text child nodes. Note that the thiskeyword in the function definition is a ref- erence to the object for which the property is calculated. And because the function runs eachtime a script statement reads the property, any scripted changes to the content after the pageloads are reflected in the returned property value. Listing 14-3: Adding a Read-Only Prototype Property to All HTMLElement Objects To access the property, use it like any other property of the object. For example: var BodyNodeDetail = document.body.childNodeDetail; The returned value in this example is an object, so you use regular JavaScript syntax toaccess one of the property values: var BodyElemNodesCount = document.body.childNodeDetail.elementNodes; Bidirectional event modelDespite the seemingly conflicting event models of NN4 (trickle down) and IE4 (bubble up), the W3C DOM event model (defined in Level 2) manages to employ both event propagationmodels. This gives the scripter the choice of where along an event s propagation path theevent gets processed. To prevent conflicts with existing event model terminology, the W3Cmodel invents many new terms for properties and methods for events. Some coding probablyrequires W3C DOM specific handling in a page aimed at multiple object models.

Disney web site - 189Chapter 14Document Object Model EssentialsChapter 15 details node

Friday, September 28th, 2007

189Chapter 14Document Object Model EssentialsChapter 15 details node properties and methods that are inherited by all HTML elements. Most are implemented in both IE5+ and W3C DOM browsers. Also look to the reference mate- rial for the documentobject in Chapter 18 for other valuable W3C DOM methods. A de facto standard: innerHTMLMicrosoft was the first to implement the innerHTMLproperty of all element objects startingwith IE4. While the W3C DOM has not supported this property, scripters frequently find itmore convenient to modify content dynamically by way of a string containing HTML markup, rather than creating and assembling element and text nodes. As a result, most modern W3CDOM browsers, including Moz1 and Safari1, support the read/write innerHTMLproperty of allelement objects as a de facto standard. When you assign a string containing HTML markup to the innerHTMLof an existing element, the browser automatically inserts the newly rendered elements into the document node tree. You may also use innerHTMLwith unmarked text to perform the equivalent of the IE-onlyinnerTextproperty. Despite the apparent convenience of the innerHTMLproperty compared to the step-by-stepprocess of manipulating element and text node objects, browsers operate on nodes muchmore efficiently than on assembly of long strings. This is one case where less JavaScript codedoes not necessarily translate to greater efficiency. Static W3C DOM HTML objectsThe Moz1 DOM (but unfortunately not IE5+) adheres to the core JavaScript notion of prototypeinheritance with respect to the object model. When a page loads into Moz1, the browser createsHTML objects based on the prototypes of each object defined by the W3C DOM. For example, ifyou use The Evaluator Sr. (Chapter 13) to see what kind of object the myPparagraph object is(enter document.getElementById( myP )into the top text box and click the Evaluate button), it reports that the object is based on the HTMLParagraphElementobject of the DOM. Every instance of a pelement object in the page inherits its default properties and methods fromHTMLParagraphElement(which, in turn, inherits from HTMLElement, Element, and Nodeobjects all detailed in the JavaScript binding appendix of the W3C DOM specification). You can use scripting to add properties to the prototypes of some of these static objects. Todo so, you must use new features added to Moz1. Two new methods __defineGetter__() and __defineSetter__() enable you to assign functions to a custom property of anobject. These methods are Mozilla-specific. To prevent their possible collision with standardizedimplementations of these features in future implementations of ECMAScript, the underscorecharacters on either side of the method name are pairs of underscore characters. The functions execute whenever the property is read (the function assigned via the__defineGetter__()method) or modified (the function assigned via the __defineSetter__()method). The common way to define these functions is in the form of an anonymousfunction (see Chapter 33). The formats for the two statements that assign these behaviorsto an object prototype are as follows: object.prototype.__defineGetter__( propName , function([param1[,…[,paramN]]]) { // statementsreturn returnValue; }) Note

188Part IIIDocument Objects ReferenceNow the (Web site template) script is ready

Friday, September 28th, 2007

188Part IIIDocument Objects ReferenceNow the script is ready to invoke the replaceChild()method on the emelement, swappingthe old text node with the new: document.getElementById( emphasis1 ).replaceChild(newText, oldChild); If you want to capture the old node before it disappears entirely, be aware that thereplaceChild()method returns a reference to the replaced node (which is only in mem- ory at this point, and not part of the document node hierarchy). You can assign the methodstatement to a variable and use that old node somewhere else, if needed. This may seem like a long way to go; it is, especially if the HTML you are generating is com- plex. Fortunately, you can take a simpler approach for replacing text nodes. All it requires is areference to the text node being replaced. You can assign that node s nodeValueproperty itsnew string value: document.getElementById( emphasis1 ).childNodes[0].nodeValue = first ; When an element s content is entirely text (for example, a table cell that already has a text nodein it), this is the most streamlined way to swap text on the fly using W3C DOM syntax. Thisdoesn t work for the creation of the second paragraph text earlier in this chapter because thetext node did not exist yet. The createTextNode()method had to explicitly create it. Also remember that a text node does not have any inherent style associated with it. The styleof the containing HTML element governs the style of the text. If you want to change not onlythe text node s text but also how it looks, you have to modify the styleproperty of the textnode s parent element. Browsers that perform these kinds of content swaps and stylechanges automatically reflow the page to accommodate changes in the size of the content. To summarize, Listing 14-2 is a live version of the modifications made to the original docu- ment shown in Listing 14-1. The new version includes a button and script that makes thechanges described throughout this discussion of nodes. Reload the page to start over. Listing 14-2: Adding/Replacing DOM Content

This is the one andonly paragraph on the page.

Web hosting uk - 187Chapter 14Document Object Model EssentialsThe new element has

Thursday, September 27th, 2007

187Chapter 14Document Object Model EssentialsThe new element has no ID, attributes, or any content. To assign some attributes to that ele- ment, you can use the setAttribute()method (a method of every element object) or assigna value to the object s corresponding property. For example, to assign an identifier to the newelement, use eithernewElem.setAttribute( id , newP ); ornewElem.id = newP ; Both ways are perfectly legal. Even though the element has an ID at this point, it is not yetpart of the document so you cannot retrieve it via the document.getElementById() method. To add some content to the paragraph, you next generate a text node as a separate object: var newText = document.createTextNode( This is the second paragraph. ); Again, this node is just sitting around in memory waiting for you to apply it as a child of someother node. To make this text the content of the new paragraph, you can append the node asa child of the paragraph element that is still in memory: newElem.appendChild(newText); If you were able to inspect the HTML that represents the new paragraph element, it wouldlook like the following:

This is the second paragraph.

The new paragraph element is ready for insertion into a document. Using the documentshown in Listing 14-1, you can append it as a child of the bodyelement: document.body.appendChild(newElem); At last, the new element is part of the document containment hierarchy. You can now refer- ence it just like any other element in the document. Replacing node contentThe addition of the paragraph shown in the last section requires a change to a portion ofthe text in the original paragraph (the first paragraph is no longer the one and only para- graph on the page). As mentioned earlier, you can perform text changes either via thereplaceChild()method or by assigning new text to a text node s nodeValueproperty. Let s see how each approach works to change the text of the first paragraph s emelementfrom one and only to first. To use replaceChild(), a script must first generate a valid text node with the new text: var newText = document.createTextNode( first ); The next step is to use the replaceChild()method. But recall that the point of view for thismethod is the parent of the child being replaced. The child here is the text node inside the emelement, so you must invoke the replaceChild()method on the emelement. Also, thereplaceChild()method requires two parameters: the first is the new node; the second is areference to the node to be replaced. Because the script statements get pretty long with thegetElementById()method, an intermediate step grabs a reference to the text node insidethe emelement: var oldChild = document.getElementById( emphasis1 ).childNodes[0];

186Part IIIDocument Objects ReferenceTable 14-6(continued) (Web hosting domain names) MethodDescriptionIE5+Moz1Safari1hasChildNodes()Determines whether current

Wednesday, September 26th, 2007

186Part IIIDocument Objects ReferenceTable 14-6(continued) MethodDescriptionIE5+Moz1Safari1hasChildNodes()Determines whether current node has YesYesYeschildren (Boolean) insertBefore(new, ref)Inserts new child in front of another childYesYesYesremoveChild(old)Deletes one childYesYesYesreplaceChild(new, old)Replaces an old child with a new oneYesYesYesisSupported(feature, Determines whether the node supports a NoYesYesversion)particular featureThe important methods for modifying content are appendChild(), insertBefore(), removeChild(), and replaceChild(). Notice, however, that all of these methods assumethat the point of view for the action is from the parent of the nodes being affected by themethods. For example, to delete an element (using removeChild()), you don t invoke thatmethod on the element being removed, but rather on its parent element. This leaves open thepossibility for creating a library of utility functions that obviate having to know too muchabout the precise containment hierarchy of an element. A simple function that lets a scriptappear to delete an element actually does so from its parent: function removeElement(elemID) { var elem = document.getElementById(elemID); elem.parentNode.removeChild(elem); } If this seems like a long way to go to accomplish the same result as setting the outerHTMLproperty of an IE4+ object to empty, you are right. While some of this convolution makessense for XML, unfortunately the W3C working group doesn t seem to have HTML scripters best interests in mind. All is not lost, however, as you see later in this chapter. Generating new node contentThe final point about the node structure of the W3C DOM focuses on the similarly gnarledway scripters must go about generating content they want to add or replace on a page. Fortext-only changes (for example, the text inside a table cell), there is both an easy and a hardway to perform the task. For HTML changes, there is only the hard way (plus a handyworkaround discussed later). Let s look at the hard way first and then pick up the easy wayfor text changes. To generate a new node in the DOM, you look to the variety of methods that are defined forthe Core DOM s documentobject (and are therefore inherited by the HTML documentobject). A node creation method is defined for nearly every node type in the DOM. The two importantones for HTML documents are createElement()and createTextNode(). The first gener- ates an element with whatever tag name (string) you pass as a parameter; the second gener- ates a text node with whatever text you pass. When you first create a new element, it exists only in the browser s memory and not as partof the document containment hierarchy. Moreover, the result of the createElement() method is a reference to an empty element except for the name of the tag. For example, tocreate a new pelement, usevar newElem = document.createElement( p );

185Chapter 14Document (Apache web server tutorial) Object Model EssentialsTable 14-6: Node Object

Tuesday, September 25th, 2007

185Chapter 14Document Object Model EssentialsTable 14-6: Node Object Methods (W3C DOM Level 2) MethodDescriptionIE5+Moz1Safari1appendChild(newChild)Adds child node to end of current nodeYesYesYescloneNode(deep)Grabs a copy of the current node (optionally YesYesYeswith children) ContinuedThe Object-Oriented W3C DOMIf you are familiar with concepts of object-oriented (OO) programming, you will appreciate theOO tendencies in the way the W3C defines the DOM. The Nodeobject includes sets of properties(see Table 14-4) and methods (see Table 14-6) that are inherited by every object based on theNode. Most of the objects that inherit the Node s behavior have their own properties and/ormethods that define their specific behaviors. The following figure shows (in W3C DOM terminol- ogy) the inheritance tree from the Noderoot object. Most items are defined in the Core DOM, while items shown in boldface are from the HTML DOM portion. W3C DOM Node object inheritance tree. You can see from the preceding figure that individual HTML elements inherit properties andmethods from the generic HTML element, which inherits from the Core Elementobject, which, in turn, inherits from the basic Node. It isn t important to know the Nodeobject inheritance to script the DOM. But it does help explainthe ECMA Script Language Binding appendix of the W3C DOM recommendation, as well as explainhow a simple element object winds up with so many properties and methods associated with it. Node+–Document| +–HTMLDocument+–CharacterData| +–Text| | +–CDATASection| +–Comment+–Attr+–Element| +–HTMLElement| +– (Each specific HTML element) +–DocumentType+–DocumentFragment+–Notation+–Entity+–Entity Reference+–ProcessingInstruction

181Chapter 14Document Object (Web hosting ecommerce) Model Essentialssimple HTML document to

Tuesday, September 18th, 2007

181Chapter 14Document Object Model Essentialssimple HTML document to see how this system works. Listing 14-1 is formatted to show thecontainment hierarchy of elements and string chunks. Listing 14-1: A Simple HTML Document

This is the one and only paragraph on the page.

What you don t see in the listing is a representation of the documentobject. The documentobject exists automatically when this page loads into a browser. Importantly, the documentobject encompasses everything you see in Listing 14-1. Therefore, the documentobject has asingle nested element: the htmlelement. The htmlelement, in turn, has two nested elements: headand body. The headelement contains the titleelement, while the titleelement con- tains a chunk of text. Down in the bodyelement, the pelement contains three pieces: a stringchunk, the emelement, and another string chunk. According to W3C DOM terminology, each container, standalone element (such as a brele- ment), or text chunk is known as a node a fundamental building block of the W3C DOM. Nodes have parent-child relationships when one container holds another. As in real life, parent-child relationships extend only between adjacent generations, so a node can have zeroor more children. However, the number of third-generation nodes further nested within thefamily tree does not influence the number of children associated with a parent. Therefore, inListing 14-1, the htmlnode has two child nodes, headand body, which are siblingsthat sharethe same parent. The bodyelement has one child (p) even though that child contains threechildren (two text nodes and an emelement node). If you draw a hierarchical tree diagram of the document in Listing 14-1, it should look like theillustration in Figure 14-3. If the document s source code contains a Document Type Definition (in a DOCTYPEelement) above the tag, the browser treats that DOCTYPEnode as a sibling of the HTML ele- ment node. In that case, the root documentnode contains two child nodes. The W3C DOM (through Level 2) defines 12 different types of nodes, 7 of which have directapplication in HTML documents. These seven types of nodes appear in Table 14-3 (the restapply to XML). Of the 12 types, the three most common are the document, element, and texttypes. All W3C DOM browsers (including IE5+, Moz1, Safari, and others) implement the threecommon node types, while Moz1 implements all of them. Note

180Part IIIDocument Objects ReferenceAny element that you intend (Web hosting domains)

Tuesday, September 18th, 2007

180Part IIIDocument Objects ReferenceAny element that you intend to script whether to change its content or its style shouldhave an identifier assigned to the element s idattribute. Form control elements still requirenameattributes if you submit the form content to a server. But you can freely assign a differ- ent identifier to a control s idattribute. Scripts can use either the idor the document. formReference.elementNamereference to reach a control object. Identifiers are essen- tially the same as the values you assign to the nameattributes of form and form input ele- ments. Following the same rules for the nameattribute value, an ididentifier must be asingle word (no white space), it cannot begin with a numeral (to avoid conflicts inJavaScript), and it should avoid punctuation symbols except for the underscore. While anelement can be accessed by numeric index within the context of some surrounding element(such as the body), this is a risky practice when content is under construction. Uniqueidentifiers make it much easier for scripts to reference objects and are not affected bychanges in content order. New DOM conceptsWith the W3C DOM come several concepts that may be entirely new to you unless you haveworked extensively with the terminology of tree hierarchies. Concepts that have the mostimpact on your scripting are new ways of referencing elements and nodes. Element referencingScript references to objects in the DOM Level 0 are observed in the W3C DOM for backwardcompatibility. Therefore, a form input element whose nameattribute is assigned the valueuserNameis addressed just like it always is: document.forms[0].userNameordocument.formName.userNameBut because all elements of a document are exposed to the documentobject, you can use thenew documentobject method to access any element whose ID is assigned. The method isdocument.getElementById(), and the sole parameter is a string version of the identifier ofthe object whose reference you wish to get. To help put this in context with what you mayhave used with the IE4 object model, consider the following HTML paragraph tag:

In IE4+, you can reference this element withvar elem = document.all.myParagraph; Although the document.allcollection is not implemented in the W3C DOM, use the newdocumentobject method (available in IE5+, Moz1+, Safari, and others) that enables you toaccess any element by its ID: var elem = document.getElementById( myParagraph ); Unfortunately for scripters, this method is difficult to type since it is case-sensitive, so watchout for that ending lowercase d . A hierarchy of nodesThe issue surrounding containers (described earlier) comes into play for the underlyingarchitecture of the W3C DOM. Every element or freestanding chunk of text in an HTML (orXML) document is an object that is contained by its next outermost container. Let s look at a