While the new mechanism supports the long-standing notion of binding an event to an element by way of HTML attributes for example, the old onClickevent handler, it encourages binding eve
Trang 1Example on the CD-ROM
Related Items:nodeNameproperty; getElementsByTagName()method
tagUrn
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
The tagUrnproperty is associated primarily with XML that is embedded within
a document When you include XML, you can specify one or more XML Namespaces that define the “owner” of a custom tag name — thus preventing conflicts of identi-cal custom tags from different sources in a document (See Chapter 33 for more about XML objects.) A Namespace definition can include a Uniform Resource Name (URN) that lets a page link to a destination on the network that further defines such Namespace aspects as a behavior associated with a custom XML element
The XML Namespace is assigned (in IE5+) as an attribute of the <HTML>tag that surrounds the entire document
<HTML XMLNS:Fred=”http://www.giantco.com/xmllib/”>
After that, the namespace value precedes all custom tags linked to that Namespace:
<Fred:FIRST_Name ID=”fredFirstName”/>
To find out the URN of the namespace “owner” of an element, you can read the tagUrnproperty of that element For the preceding example, the tagURNproperty returns www.giantco.com/xmllib For regular HTML elements, the returned value
is always null The corresponding property in the W3C DOM and NN6 is namespaceURI
Example on the CD-ROM
Related Item:scopeNameproperty
title
On the
CD-ROM
On the
CD-ROM
elementObject.title
Trang 2NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
The W3C standard states that you should use the titleproperty (and TITLE
attribute) in an “advisory” role The main browsers interpret that role as text
assigned to tooltips that pop up momentarily while the cursor rests atop an
ele-ment The advantage of having this property available for writing is that your
scripts can modify an element’s tooltip text in response to other user interaction on
the page
A tooltip can provide brief help about the behavior of icons or links on the page
It can also convey a summary of key facts from the destination of a link, thus
enabling a visitor to see vital information without having to navigate to the other
page For example, Microsoft’s Web authoring documentation online (http://
msdn.microsoft.com) uses the tooltips in listings of scriptable properties to
dis-play a list of elements for which the property is available While this information
also appears on the destination of the link for each property, you can see at a
glance, for instance, which instance of the two listings for the same property name
apply to the object in which you’re interested The browser governs tooltip font
and color characteristics, which are not changeable via scripting
As with setting the status bar, I don’t recommend using tooltips for conveying
mission-critical information to the user Not all users are patient enough to let the
pointer pause for the tooltip to appear On the other hand, a user may be more
likely to notice a tooltip once it appears rather than a status bar message (even
though the latter appears instantaneously)
Example (with Listing 15-17) on the CD-ROM
Related Item:window.statusproperty
uniqueID
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
You can let the IE5+/Windows browser generate an identifier (idproperty) for a
dynamically generated element on the page with the aid of the uniqueIDproperty
You should use this feature with care because the ID it generates at any given time
may differ from the ID generated the next time the element is created in the page
Therefore, you should use the uniqueIDproperty when your scripts require an
unknown element to have an idproperty but the algorithms are not expecting any
specific identifier
On the
CD-ROM
elementObject.uniqueID
Trang 3To guarantee that an element gets only one ID assigned to it while the object exists in memory, assign the value via the uniqueIDproperty of that same object — not some other object Once you retrieve the uniqueIDproperty of an object, the property’s value stays the same no matter how often you access the property again
In general, you assign the value returned by the uniqueIDproperty to the object’s
idproperty for other kinds of processing (For example, the parameter of a getElementById()method requires the value assigned to the idproperty of an object.)
Example (with Listing 15-18) on the CD-ROM
Related Items:idproperty; getElementById()method
Methods
addBehavior(“URL”)
Returns: Integer ID.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
The addBehavior()method imports an external Internet Explorer behavior and attaches it to the current object, thereby extending the properties and/or methods
of that object See Chapter 48 for details on IE behaviors (new in IE5 for Windows) The sole parameter of the addBehavior()method is a URL pointer to the behavior component’s code This component may be in an external file (with an htcextension), in which case the parameter can be a relative or absolute URL IE also includes a library of built-in (default) behaviors, whose URLs are in the follow-ing format:
#default#behaviorName
Here, behaviorNameis one of the default behaviors (see Chapter 48) If the behavior is imported into the document via the OBJECTtag, the addBehavior() method parameter is the ID of that element in the following format:
#objectID
When you add a behavior, the loading of the external code occurs asyn-chronously This means that even though the method returns a value instantly, the behavior is not necessarily ready to work Only when the behavior is fully loaded can it respond to events or allow access to its properties and methods Behaviors loaded from external files observe domain security rules The behavior component and the HTML page that loads it must come from the same server and domain; they also must load via the same protocol (for example, http://, https://, and file://are mutually exclusive, mismatched protocols)
On the
CD-ROM
elementObject.addBehavior()
Trang 4Example (with Listings 15-19a and 15-19b) on the CD-ROM
Related Items:readyStateproperty; removeBehavior()method; behaviors
(Chapter 48)
addEventListener(“eventType”,
listenerFunc, useCapture)
removeEventListener(“eventType”,
listenerFunc, useCapture)
Returns: Nothing.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Compatibility ✓
The W3C DOM’s event mechanism accommodates both event bubbling and
trick-ling (see Chapter 29) While the new mechanism supports the long-standing notion
of binding an event to an element by way of HTML attributes (for example, the old
onClickevent handler), it encourages binding events by registering an event
lis-tener with an element (In browsers that support the W3C event model, other ways
of binding events — such as event handler attributes — are internally converted to
registered events.)
To tell the DOM that an element should “listen” for a particular kind of event, use
the addEventListener()method on the element object The method requires
three parameters The first is a string version of the event type for which the
ele-ment should listen Event type strings do not include the well-used “on” prefix of
event handlers Instead, the names consist only of the event and are usually in all
lowercase (except for some special system-wide events preceded by DOM) Table
15-7 shows all the events recognized by the W3C DOM specification (although NN6
may not implement them all)
Table 15-7 W3C DOM Event Listener Types
Continued
On the
CD-ROM
elementObject.addEventListener()
Trang 5Table 15-7 (continued)
DOMCharacterDataModified mouseover
DOMNodeInsertedIntoDocument scroll
DOMNodeRemovedFromDocument submit DOMSubtreeModified unload
Note that the event types specified in the DOM Level 2 are more limited than the wide range of events defined in IE4+ Also, the W3C temporarily tabled the issue of keyboard events until DOM Level 3 Fortunately, Netscape implements keyboard events in a fashion that likely will appear as part of the W3C DOM
The second parameter of the addEventListener()method is a reference to the JavaScript function to be invoked This is the same form used to assign a func-tion to an event property of an object (for example, objReference.onclick = someFunction ), and it should not be a quoted string This approach also means
that you cannot specify parameters in the function call Therefore, functions that need to reference forms or form control elements must build their own references (with the help of the event object’s property that says which object is the event’s target)
By default, the W3C DOM event model has events bubble upward through the element container hierarchy starting with the target object of the event (for exam-ple, the button being clicked) However, if you specify truefor the third parameter
of the addEventListener()method, event capture is enabled for this particular event type whenever the current object is the event target This means that any other event type targeted at the current object bubbles upward unless it, too, has
an event listener associated with the object and the third parameter is set to true NN6 does not always set event capture for an element, even when you specify trueas the third parameter of addEventListener() For the most part, you can make do with event bubbling by adding an event listener to a container higher
up the element hierarchy Because event capture is a part of the W3C DOM event model, this feature will likely be implemented in a future version of NN
Using the addEventListener() method requires that the object to which it is attached already exist Therefore, you most likely will use the method inside an initialization function triggered by the onLoadevent handler for the page (The documentobject can use addEventListener()for the load event immediately because the documentobject exists early in the loading process.)
Caution
elementObject.addEventListener()
Trang 6A script can also eliminate an event listener that was previously added by script.
The removeEventListener()method takes the same parameters as
addEventListener(), which means that you can turn off one listener without
dis-turbing others In fact, because you can add two listeners for the same event and
listener function (one set to capture and one not — a rare occurrence, indeed), the
three parameters of the removeEventListener()enable you to specify precisely
which listener to remove from an object
Unlike the event capture mechanism of NN4, the W3C DOM event model does not
have a “global” capture mechanism for an event type regardless of target And with
respect to IE5, the addEventListener()method is closely analogous to the IE5
attachEvent()method Also, event capture in IE5 is enabled via the
setCapture()method Both the W3C and IE5 event models use their separate
syn-taxes to bind objects to event handling functions, so the actual functions may be
capable of serving both models with browser version branching required only for
event binding See Chapter 29 for more about event handling with these two event
models
Example (with Listing 15-20) on the CD-ROM
Related Items:attachEvent(), detachEvent(), dispatchEvent(),
fireEvent(), removeEventListener()methods
appendChild(nodeObject)
Returns: Node object reference.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Using the W3C DOM parent, node, and child terminology, you can create
cross-browser code (for IE5+ and NN6) that modifies HTML content on the page The
appendChild()method inserts an element or text node (defined by other code
that comes before it) as the new, last child of the current element
Aside from the more obvious application of adding a new child element to the
end of a sequence of child nodes, the appendChild()method is also practical for
building element objects and their content before appending, replacing, or inserting
the element into an existing document The document.createElement()method
generates a reference to an element of whatever tag name you assign as that
method’s parameter But this does nothing to populate the element’s attributes or
its content While IE4+ offers nonstandard innerTextand innerHTMLshortcut
properties to assign content to an element (and NN6 provides innerHTML), the
DOM standard recommends adding child nodes to the new element (for more
details, see Chapter 14) For example, if you wish to create a B element and its
content, you first create the element and then append a text node, as in the
follow-ing sequence:
On the
CD-ROM
elementObject.appendChild()
Trang 7var newB = document.createElement(“B”) newB.appendChild(document.createTextNode(“Important!”))
At this point, you can append or insert the newBelement It appears with its content ready to go
The appendChild()method returns a reference to the appended node object This reference differs from the object that is passed as the method’s parameter because the returned value represents the object as part of the document rather than as a freestanding object in memory
Example (with Listing 15-21) on the CD-ROM
Related Items:removeChild(), replaceChild()methods; nodes and children (Chapter 14)
applyElement(elementObject[, type])
Returns: Nothing.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
The applyElement()method (not implemented in IE5/Mac) enables you to insert a new element as the parent or child of the current object An important feature of this method is that the new object is wrapped around the current object (if the new element is to become the parent) or the current object’s content (if the new element is to become a child) When the new element becomes a child, all pre-vious children are nested further by one generation to become immediate children
of the new element You can imagine how the resulting action of this method affects the containment hierarchy of the current element, so you must be careful in how you use the applyElement()method
One parameter, a reference to the object to be applied, is required This object may be generated from constructions such as document.createElement()or from one of the child or node methods that returns an object The second parame-ter is optional, and it must be one of the following values:
Parameter Value Description
outside New element becomes the parent of the current object inside New element becomes the immediate child of the current object
If you omit the second parameter, the default value (outside) is assumed
On the
CD-ROM
elementObject.applyElement()
Trang 8Example (with Listing 15-22) on the CD-ROM
Related Items:insertBefore(), appendChild(), insertAdjacentElement()
methods
attachEvent(“eventName”, functionRef)
detachEvent(“eventName”, functionRef)
Returns: Boolean.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
The attachEvent()method is used primarily within code that specifies IE
behaviors (see Chapter 48) But you can also use it in regular scripting as yet
another way to bind an event handler to an object The following example
charac-terizes the more typical approach to assigning an event handler:
myObject.onmousedown = setHilite
The version with attachEvent()is as follows:
myObject.attachEvent(“onmousedown”, setHilite)
Both parameters are required The first parameter is a string version
(case-insensitive) of the event name The second is a reference to the function to be
invoked when the event fires for this object A function reference is an unquoted,
case-sensitive identifier for the function without any parentheses (which also
means that you cannot pass parameters in this function call)
There is a subtle benefit to using attachEvent()over the event property
bind-ing approach When you use attachEvent(), the method returns a Boolean value
of trueif the event binding succeeds IE triggers a script error if the function
refer-ence fails, so don’t rely on a returned value of falseto catch these kinds of errors
Also, there is no validation that the object recognizes the event name
If you have used attachEvent()to bind an event handler to an object’s event,
you can disconnect that binding with the detachEvent()method The parameters
are the same as for attachEvent() The detachEvent()method cannot unbind
events whose associations are established via tag attributes or event property
settings
The W3C DOM event model provides functionality similar to these IE-only
meth-ods: addEventListener()and removeEventListener()
Example on the CD-ROM
On the
CD-ROM
On the
CD-ROM
elementObject.attachEvent()
Trang 9Related Items:addEventListener(), detachEvent(), dispatchEvent(), fireEvent(), removeEventListener()methods; Event binding (Chapter 14)
blur()
focus()
Returns: Nothing.
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5 Compatibility ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓
The blur()method removes focus from an element, while the focus()method gives focus to an element Even though the blur()and focus()methods have been around since the earliest scriptable browsers, not every focusable object has enjoyed these methods since the beginning Browsers prior to IE4 and NN6 limited these methods primarily to the windowobject and form control elements
Windows
For window objects, the blur()method (NN3+, IE4+) pushes the referenced win-dow to the back of all other open winwin-dows If other browser suite winwin-dows (such as e-mail or news reader windows) are open, the window receiving the blur()method
is placed behind these windows as well
The window.blur() method does not adjust the stacking order of the current window in NN6 But a script in a window can invoke the focus() method of another window to bring that other window to the front (provided a scriptable linkage, such as the window.opener property, exists between the two windows) The minute you create another window for a user in your Web site environment, you must pay attention to window layer management With browser windows so easily activated by the slightest mouse click, a user can lose a smaller window behind a larger one in a snap Most inexperienced users don’t think to check the Windows taskbar or browser menu bar (if the browser is so equipped) to see if a smaller window is still open and then activate it If that subwindow is important to your site design, then you should present a button or other device in each window that enables users to safely switch among windows The window.focus()method brings the referenced window to the front of all the windows
Rather than supply a separate button on your page to bring a hidden window forward, you should build your window-opening functions in such a way that if the window is already open, the function automatically brings that window forward (as shown in Listing 15-23) This removes the burden of window management from your visitors
The key to success with this method is making sure that your references to the desired windows are correct Therefore, be prepared to use the window.opener property to refer to the main window if a subwindow needs to bring the main window back into focus
Caution
elementObject.blur()
Trang 10Form elements
The blur()and focus()methods apply primarily to text-oriented form
con-trols: text input, SELECT, and TEXTAREA elements
Just as a camera lens blurs when it goes out of focus, a text object “blurs” when
it loses focus — when someone clicks or tabs out of the field Under script control,
blur()deselects whatever may be selected in the field, and the text insertion
pointer leaves the field The pointer does not proceed to the next field in tabbing
order, as it does if you perform a blur by tabbing out of the field manually
For a text object, having focus means that the text insertion pointer is flashing in
that text object’s field Giving a field focus is like opening it up for human editing
Setting the focus of a text field or TEXTAREA does not, by itself, enable you to
place the cursor at any specified location in the field The cursor usually appears at
the beginning of the text To prepare a field for entry to remove the existing text,
use both the focus()and select()methods in series Be aware, however, that the
focus()method does not work reliably in Navigator 3 for UNIX clients: While the
select()method selects the text in the designated field, focus is not handed to
the field
One other caveat about using focus()and select()together to preselect the
content of a text field for immediate editing: Many versions of Internet Explorer fail
to achieve the desired results due to an internal timing problem You can work
around this problem (and remain compatible with Navigator) by initiating the
focus and selection actions through a setTimeout()method See Chapter 43 on
data validation for an example
A common design requirement is to position the insertion pointer at the end of a
text field or TEXTAREA so that a user can begin appending text to existing content
immediately This is possible in IE4+ with the help of the TextRangeobject The
fol-lowing script fragment moves the text insertion pointer to the end of a TEXTAREA
element whose ID is myTextarea:
var range = document.all.myTextarea.createTextRange()
range.move(“textedit”)
range.select()
You should be very careful in combining blur()or focus()methods with
onBlurand onFocusevent handlers — especially if the event handlers display alert
boxes Many combinations of these events and methods can cause an infinite loop
in which it is impossible to dismiss the alert dialog box completely On the other
hand, there is a useful combination for older browsers that don’t offer a disabled
property for text boxes The following text field event handler can prevent users
from entering text in a text field:
onFocus = “this.blur()”
Some operating systems and browsers enable you to give focus to elements such
as buttons (including radio and checkbox buttons) and hypertext links
(encom-passing both A and AREA elements) Typically, once such an element has focus, you
can accomplish the equivalent of a mouse click on the element by pressing the
spacebar on the keyboard This is helpful for accessibility to those who have
diffi-culty using a mouse
elementObject.blur()