Archive for September, 2007

Photo web hosting - 169Chapter 14Document Object Model Essentials the value of

Monday, September 10th, 2007

169Chapter 14Document Object Model Essentials the value of the object s onfocus(all lowercase) property isfunction onfocus() { doIt(); } You can, however, assign an entirely different function to an event handler by assigning afunction reference to the property. Such references don t include the parentheses that arepart of the function s definition. (You see this again much later in Chapter 33 when you assignfunctions to object properties.) Using the same text field definition you just looked at, you can assign a different function tothe event handler because based on user input elsewhere in the document you want the fieldto behave differently when it receives the focus. If you define a function like this: function doSomethingElse() { statements} you can then assign the function to the field with this assignment statement: document.formName.entry.onfocus = doSomethingElse; Because the new function reference is written in JavaScript, you must observe case for the func- tion name. Although NN4 accepts interCap versions of the event handler names, you are bestserved across all browsers by sticking with all lowercase event handler names as properties. Be aware, however, that as with several settable object properties that don t manifest them- selves visually, any change you make to an event handler property disappears with a docu- ment reload. Therefore, I advise you not to make such changes except as part of a script thatalso invokes the event handler like a method: Any gap in time leaves room for users toreload the page accidentally or intentionally. If your scripts create new element objects dynamically, you can assign event handlers tothese objects by way of event handler properties. For example, the following code uses W3CDOM syntax to create a new button input element and assign an onclickevent handler thatinvokes a function defined elsewhere in the script: var newElem = document.createElement( input ); newElem.type = button ; newElem.value = Click Here ; newElem.onclick = doIt; document.forms[0].appendChild(newElem); Because every event handler operates as both property and method, I don t list these proper- ties and methods as part of each object s definition in the next chapters. You can be assuredthis feature works for every JavaScript object that has an event handler starting withNavigator 3 and Internet Explorer 4. Object Model SmorgasbordA survey of the entire evolution of scriptable browsers from NN2 and IE3 through IE6 andMoz1 reveals six (yes, six!) distinct document object model families. Even if your job entailsdeveloping content for just one current browser version, you may be surprised that familymembers from more than one document object model inhabit your authoring space. Caution

168Part IIIDocument Objects ReferenceObject Event HandlersAnevent handlerspecifies how (Managed web hosting)

Sunday, September 9th, 2007

168Part IIIDocument Objects ReferenceObject Event HandlersAnevent handlerspecifies how an object reacts to an event that is triggered by a useraction (for example, a button click) or a browser action (for example, the completion of adocument load). Going back to the earliest JavaScript-enabled browser, event handlerswere defined inside HTML tags as extra attributes. They included the name of the attribute, followed by an equal sign (working as an assignment operator) and a string containing thescript statement(s) or function(s) to execute when the event occurs (see Chapter 5). Eventhandlers also have other forms. In NN3+ and IE4+, event handlers have correspondingmethods for their objects and every event handler is a property of its object. Event handlers as methodsConsider a button object whose sole event handler is onclick. This means whenever the but- ton receives a click event, the button triggers the JavaScript expression or function callassigned to that event handler in the button s HTML definition: Normally, that click event is the result of a user physically clicking the button in the page. InNN3+ and IE4+, you can also trigger the event handler with a script by calling the event han- dler as if it were a method of the object: document.formName.clicker.onclick(); Invoking an event handler this way is different from using a method to simulate the physicalaction denoted by the event. For example, imagine a page containing three simple text fields. One of those fields has an onfocusevent handler defined for it. Physically tabbing to or click- ing in that field brings focus to the field and thereby triggers its onfocusevent handler. If thefield does not have focus, a button can invoke that field s onfocusevent handler by referenc- ing it as a method: document.formName.fieldName.onfocus(); This scripted action does not bring physical focus to the field. The field s own focus() method, however, does that under script control. A byproduct of an event handler s capability to act like a method is that you can define theaction of an event handler by defining a function with the event handler s name. For example, instead of specifying an onloadevent handler in a document s tag, you can define afunction like this: function onload() { statements} This capability is particularly helpful if you want event handler actions confined to a scriptrunning in NN3, IE4, or later. Your scripts don t require special traps for Navigator 2 orInternet Explorer 3. Event handlers as propertiesAlthough event handlers are commonly defined in an object s HTML tag, you also have thepower in NN3+ and IE4+ to assign or change an event handler just like you assign or changethe property of an object. The value of an event handler property looks like a function defini- tion. For example, given this HTML definition:

167Chapter 14Document Object Model EssentialsObject MethodsAn object s (Most popular web site) method

Sunday, September 9th, 2007

167Chapter 14Document Object Model EssentialsObject MethodsAn object s method is a command that a script can give to that object. Some methods returnvalues, but that is not a prerequisite for a method. Also, not every object has methodsdefined for it. In a majority of cases, invoking a method from a script causes some action totake place. The resulting action may be obvious (such as resizing a window) or somethingmore subtle (such as sorting an array in memory). All methods have parentheses after them, and they always appear at the end of an object sreference. When a method accepts or requires parameters, the parameter values go insidethe parentheses (with multiple parameters separated by commas). While an object has its methods predefined by the object model, you can also assign one ormore additional methods to an object that already exists (that is, after its HTML is loadedinto the document). To do this, a script in the document (or in another window or frameaccessible by the document) must define a JavaScript function and then assign that functionto a new property name of the object. In the following example written to take advantage ofversion 4 or later browser features, the fullScreen()function invokes one windowobjectmethod and adjusts two windowobject properties. By assigning the function reference to thenew window.maximizeproperty, I define a maximize()method for the windowobject. Thus, a button s event handler can call that method directly. // define the functionfunction fullScreen() { this.moveTo(0,0); this.outerWidth = screen.availWidth; this.outerHeight = screen.availHeight; } // assign the function to a custom propertywindow.maximize = fullScreen; … A Note to Experienced Object-Oriented ProgrammersAlthough the basic object model hierarchy appears to have a class/subclass relationship, many ofthe traditional aspects of a true, object-oriented environment don t apply to the model. The orig- inal JavaScript document object hierarchy is a containmenthierarchy, not an inheritancehierar- chy. No object inherits properties or methods of an object higher up the chain. Nor is there anyautomatic message passing from object to object in any direction. Therefore, you cannot invokea window s method by sending a message to it via the documentor a form object. All object ref- erences must be explicit. Predefined document objects are generated only when the HTML code containing their defini- tions loads into the browser. You cannot modify many properties, methods, and event handlersin early object models once you load the document into the browser. In Chapter 33, you learnhow to create your own objects, but those objects do not present new visual elements on thepage that go beyond what HTML, Java applets, and plug-ins can portray. Inheritance doesplay a role, as you will see later in this chapter, in the object model defined bythe W3C. The new hierarchy is of a more general nature to accommodate requirements of XMLas well as HTML. But the containment hierarchy for HTML objects, as described in this section, isstill valid in W3C DOM-compatible browsers.

166Part IIIDocument Objects ReferenceThe only visible differences to (Web host 4 life)

Saturday, September 8th, 2007

166Part IIIDocument Objects ReferenceThe only visible differences to the HTML code for defining those objects are the one or moreoptional attributes specifically dedicated to JavaScript. By and large, these attributes specifythe event you want the user interface element to react to and what JavaScript should dowhen the user takes that action. By relying on the document s HTML code to perform theobject generation, you can spend more time figuring out how to do things with those objectsor have them do things for you. Bear in mind that objects are created in their load order. And if you create a multiframe envi- ronment, a script in one frame cannot communicate with another frame s objects until bothframes load. This trips up a lot of scripters who create multiframe and multiwindow sites(more in Chapter 16). Object PropertiesA property generally defines a particular current setting of an object. The setting mayreflect a visible attribute of an object, such as the state of a checkbox (checked or not); itmay also contain information that is not so obvious, such as the action and method of asubmitted form. Document objects have most of their initial properties assigned by the attribute settings ofthe HTML tags that generate the objects. Thus, a property may be a word (for example, aname) or a number (for example, a size). A property can also be an array, such as an arrayof images contained by a document. If the HTML does not include all attributes, thebrowser usually fills in a default value for both the attribute and the correspondingJavaScript property. When used in script statements, property names are case-sensitive. Therefore, if you see aproperty name listed as bgColor, you must use it in a script statement with that exactcombination of lowercase and uppercase letters. But when you set an initial value of aproperty by way of an HTML attribute, the attribute name (like all of HTML) is not case- sensitive. Thus, and both set thesame bgColorproperty value. Although XHTML won t validate correctly if you use any- thing but lowercase letters for tag and attribute names, most browsers continue to becase-insensitive for markup, regardless of the HTML or XHTML version you specify for thepage s DOCTYPE. The case for property names is not influenced by the case of the markupattribute name. Each property determines its own read/write status. Some properties are read-only, whereasyou can change others on the fly by assigning a new value to them. For example, to put somenew text into a text box object, you assign a string to the object s valueproperty: document.forms[0].phone.value = 555-1212 ; Once an object contained by the document exists (that is, its HTML is loaded into the docu- ment), you can also add one or more custom properties to that object. This can be helpful ifyou wish to associate some additional data with an object for later retrieval. To add such aproperty, simply specify it in the same statement that assigns a value to it: document.forms[0].phone.delimiter = - ; Any property you set survives as long as the document remains loaded in the window andscripts do not overwrite the object. Be aware, however, that reloading the page usuallydestroys custom properties.

165Chapter 14Document Object Model Essentialswith resides within the (Web design)

Friday, September 7th, 2007

165Chapter 14Document Object Model Essentialswith resides within the browser application. With few exceptions, a script does not accessanything about your computer hardware, operating system, other applications, desktop, orany other stuff beyond the browser program. The browser document object road mapFigure 14-1 shows the lowest common denominator document object hierarchy that is imple- mented in all scriptable browsers. Notice that the windowobject is the topmost object in theentire scheme. Everything you script in JavaScript is in the browser s window. Figure 14-1:The lowest common denominator browser document object hierarchy. Pay attention to the shading of the concentric rectangles. Every object in the same shadedarea is at the same level relative to the windowobject. When a line from an object extends tothe next darker shaded rectangle, that object contains all the objects in darker areas. Thereexists, at most, one of these lines between levels. The windowobject contains the documentobject; the documentobject contains a form object; a form object contains many differentkinds of form control elements. Study Figure 14-1 to establish a mental model for the basic scriptable elements of a Webpage. Models of more recent browsers have more objects in their hierarchies, but the fun- damental organization remains. After you script these objects several times, the objecthierarchy will become second nature to you even if you don t necessarily rememberevery detail (property, method, and event handler) of every object. At least you knowwhere to look for information. How Document Objects Are BornMost of the objects that a browser creates for you are established when an HTML documentloads into the browser. The same kind of HTML code you use to create links, anchors, andinput elements tells a JavaScript-enhanced browser to create those objects in memory. Theobjects are there whether or not your scripts call them into action. windowframe self top parenthistory document location text radio button selecttextarea checkbox reset optionlink form anchor password submit

Space web hosting - 164Part IIIDocument Objects ReferenceHierarchy as road mapFor the

Thursday, September 6th, 2007

164Part IIIDocument Objects ReferenceHierarchy as road mapFor the programmer, the primary role of the document object hierarchy is to provide scriptswith a way to reference a particular object among all the objects that a browser window cancontain. The hierarchy acts as a road map the script can use to know precisely which objectto address. Consider, for a moment, a scene in which you and your friend Tony are in a high school class- room. It s getting hot and stuffy as the afternoon sun pours in through the wall of windows onthe west side of the room. You say to Tony, Would you please open a window? and motionyour head toward a particular window in the room. In programming terms, you ve issued acommand to an object (whether or not Tony appreciates the comparison). This human inter- action has many advantages over anything you can do in programming. First, by making eyecontact with Tony before you speak, he knows that he is the intended recipient of the com- mand. Second, your body language passes along some parameters with that command, point- ing ever so subtly to a particular window on a particular wall. If, instead, you are in the principal s office using the public address system, and you broad- cast the same command, Would you please open a window?, no one knows what you mean. Issuing a command without directing it to an object is a waste of time because every objectthinks, That can t be meant for me. To accomplish the same goal as your one-on-one com- mand, the broadcast command has to be something like, Would Tony Jeffries in Room 312please open the middle window on the west wall? Let s convert this last command to JavaScript dot syntaxform (see Chapter 4). Recall from thetutorial that a reference to an object starts with the most global point of view and narrows tothe most specific point of view. From the point of view of the principal s office, the locationhierarchy of the target object isroom312.Jeffries.TonyYou can also say that Tony s knowledge about how to open a window is one of Tony s meth- ods. The complete reference to Tony and his method then becomesroom312.Jeffries.Tony.openWindow() Your job isn t complete yet. The method requires a parameter detailing which window toopen. In this case, the window you want is the middle window of the west wall of Room 312. Or, from the hierarchical point of view of the principal s office, it becomesroom312.westWall.middleWindowThis object road map is the parameter for Tony s openWindow()method. Therefore, theentire command that comes over the PA system isroom312.Jeffries.Tony.openWindow(room312.westWall.middleWindow) If, instead of barking out orders while sitting in the principal s office, you attempt the sametask via radio from an orbiting space shuttle to all the inhabitants on Earth, imagine howlaborious your object hierarchy is. The complete reference to Tony s openWindow()methodand the window that you want opened has to be mighty long to distinguish the desiredobjects from the billions of objects within the space shuttle s view. The point is that the smaller the scope of the object-oriented world you re programming, themore you can assume about the location of objects. For client-side JavaScript, the scope is nowider than the browser itself. In other words, every object that a JavaScript script can work

Document ObjectModel EssentialsWithout question, the (Christian web host) biggest challenge facing

Thursday, September 6th, 2007

Document ObjectModel EssentialsWithout question, the biggest challenge facing client-side Webscripters is the sometimes-baffling array of document objectmodels that have competed for our attention throughout the short his- tory of scriptable browsers. Netscape got the ball rolling in Navigator 2with the first object model. By the time the version 4 browsers camearound, the original object model had gained not only some usefulcross-browser features, but also a host of features that were unique toonly Navigator or Internet Explorer. The object models were diverging, causing no end of headaches for page authors whose scripts had torun on as many browsers as possible. A ray of hope emerged from thestandards process of the World Wide Web Consortium (W3C) in theform of a document object model (DOM) recommendation. The DOMbrought forward much of the original object model, plus new ways ofaddressing every object in a document. The goal of this chapter is toput each of the object models into perspective and help you select themodel(s) you intend to support in your Web applications. But beforewe get to those specifics, let s examine the role of the object model indesigning scripted applications. The Object Model HierarchyIn the tutorial chapters of Part II, you were introduced to the funda- mental ideas behind a document object hierarchy in scriptablebrowsers. In other object-oriented environments, object hierarchyplays a much greater role than it does in JavaScript-able browsers. (In JavaScript, you don t have to worry about related terms, such asclasses, inheritance, and instances.) Even so, you cannot ignore thehierarchy concept because much of your code relies on your abilityto write references to objects that depend on their positions withinthe hierarchy. Calling these objects JavaScript objects is not entirely correct. Theseare really browser document objects: you just happen to use theJavaScript language to bring them to life. Some scripters of MicrosoftInternet Explorer use the VBScript language to script the very samedocument objects. Technically speaking, JavaScript objects apply todata types and other core language objects separate from the docu- ment. The more you can keep document and core language objectsseparate in your head, the more quickly you can deal with browserbrand compatibility issues. 1414CHAPTER …In This ChapterObject models versusbrowser versionsProprietary modelextensionsStructure of the W3C DOMMixing object models single document …

161Chapter 13JavaScript Essentials .A line terminator (Photo web hosting) is usually

Wednesday, September 5th, 2007

161Chapter 13JavaScript Essentials .A line terminator is usually treated as a statement delimiter.Except in very rare con- structions, JavaScript parsers automatically insert the semicolon statement delimiterwhenever they encounter one or more line terminators (for example, carriage returnsor line feeds). A semicolon delimiter is required between two statements on the samephysical line of source code. Moreover, string literals may not have carriage returns intheir source code (but an escaped newline character (n) may be a part of the string). Onward to Object ModelsThe core language is only a small part of what you work with while scripting Web pages. Thebulk of your job entails understanding the ins and outs of document object models as imple- mented in several generations of browsers. That s where the next chapter picks up the essentials story. …

160Part IIIDocument Objects (Web design templates) Referenceprototype. Scripts can freely override

Tuesday, September 4th, 2007

160Part IIIDocument Objects Referenceprototype. Scripts can freely override prototype property values or assign differentfunctions to prototype methods in a working object if desired without affecting thestatic object prototype. But if inherited properties or methods are not modified in thecurrent working object, any changes to the static object s prototype are reflected in theworking object. (The mechanism is that a reference to an object s property works itsway up the prototype inheritance chain to find a match to the property name.) .JavaScript includes a large set of operators.You can find most operators that you areaccustomed to working with in other languages. .JavaScript provides typical control structures.All versions of JavaScript offer if, if-else, for, and whileconstructions. JavaScript 1.2 (NN4+ and IE4+) added do-whileand switchconstructions. Iteration constructions provide breakand continuestatements to modify control structure execution. .JavaScript functions may or may not return a value.There is only one kind ofJavaScript function. A value is returned only if the function includes a returnkeywordfollowed by the value to be returned. Return values can be of any data type. .JavaScript functions cannot be overloaded.A JavaScript function accepts zero or morearguments, regardless of the number of parameter variables defined for the function. Allarguments are automatically assigned to the argumentsarray, which is a property of afunction object. Parameter variable data types are not predefined. .Values are passed by reference and by value. An object passed to a function isactually a reference to that object, offering full read/write access to properties and meth- ods of that object. But other types of values (including object properties) are passed byvalue, with no reference chain to the original object. Thus, the following nonsense frag- ment empties the text box when the onchangeevent fires: function emptyMe(arg1) { arg1.value = ; } … But in the following version, nothing happens to the text box: function emptyMe(arg1) { arg1 = ; } … The local variable (arg1) simply changes from Howdy to an empty string. .Error trapping techniques depend on JavaScript version.There is no error trappingin NN2 or IE3. Error trapping in NN3, NN4, and IE4 is event-driven in the Web browserobject model. JavaScript, as implemented in IE5+ and Moz1+, Safari, and other recentbrowsers, supports try-catchand throwstatements, as well as built-in error objectsthat are not dependent on the host environment. .Memory management is not under script control.The host environment managesmemory allocation, including garbage collection. Different browsers may handle mem- ory in different ways. .White space (other than a line terminator) is insignificant.Space and tab charactersmay separate lexical units (for example, keywords, identifiers, and so on).

159Chapter 13JavaScript Essentials .JavaScript is loosely (Fedora web server) typed.Variables, arrays,

Tuesday, September 4th, 2007

159Chapter 13JavaScript Essentials .JavaScript is loosely typed.Variables, arrays, and function return values are notdefined to be of any particular data type. In fact, an initialized variable can hold differ- ent data type values in subsequent script statements (obviously not good practice, butpossible nonetheless). Similarly, an array may contain values of multiple types. Therange of built-in data types is intentionally limited: Boolean (trueor false) Null Number (double-precision 64-bit format IEEE 734 value) Object (encompassing the Arrayobject) String Undefined .The host environment defines global scope.Web browsers traditionally define abrowser window or frame to be the global context for script statements. When a doc- ument unloads, all global variables defined by that document are destroyed. .JavaScript variables have either global or local scope. A global variable in a Webbrowser is typically initialized in varstatements that execute as the document loads. All statements in that document can read or write that global variable. A local variableis initialized inside a function (also with the varoperator). Only statements inside thatfunction may access that local variable. .Scripts sometimes access JavaScript static object properties and methods.Somestatic objects encourage direct access to their properties or methods. For example, allproperties of the Mathobject act as constant values (for example, Math.PI). .You can add properties or methods to working objects at will.To add a property toan object, simply assign a value of any type to it. For example, to add an authorprop- erty to a string object named myText, use: myText.author = Jane ; Assign a function reference to an object property to give that object a new method: // function definitionfunction doSpecial(arg1) { // statements} // assign function reference to method namemyObj.handleSpecial = doSpecial; … // invoke methodmyObj.handleSpecial(argValue); Inside the function definition, the thiskeyword refers to the object that owns themethod. .JavaScript objects employ prototype-based inheritance.All object constructors cre- ate working objects whose properties and methods inherit the properties and methodsdefined for the prototypeof that object. Starting with NN3 and late versions of IE3, scripts can add and delete custom properties and/or methods associated with thestatic object s prototype so that new working objects inherit the current state of the