Main Page

Getting the target

Getting the target
The object at the center of an event is called the
target
. Suppose that you assigned an
onclick
event han-
dler to a
<div/>
element. When the
click
events fires, the
<div/>
element is considered the target.
In IE, the target is contained in the
srcElement
property of the
event
object:
var oTarget = oEvent.srcElement;
In DOM-compliant browsers, the target is contained in the
target
property:
var oTarget = oEvent.target;
Getting the character code
Earlier you saw that both IE and the DOM support an
event
object property called
keyCode
, which
returns a numeric code for the key that was pressed. If the key represents a character (unlike Shift, Ctrl,
and so on), IE’s
keyCode
property returns the character code of the character (which is its Unicode
equivalent):
var iCharCode = oEvent.keyCode;
In DOM-compliant browsers, a separation occurs between the code of the key that was pressed and the
character code. To get the character code, use the
charCode
property:
var iCharCode = oEvent.charCode;
You can then use this value to get the actual character by passing it to the
String.fromCharCode()
method:
var sChar = String.fromCharCode(oEvent.charCode);
If you are unsure as to whether the key that was pressed contains a character, you can use the
isChar
property:
if (oEvent.isChar) {
var iCharCode = oEvent.charCode;
}
IE targets can only be elements,
document
, or
window
; DOM-compliant browsers
also allow text nodes to be targets.
IE on Macintosh also supports both the
srcElement
and
target
attributes.
277
All about Events
12_579088 ch09.qxd 3/28/05 11:39 AM Page 277


JavaScript EditorFree JavaScript Editor     Ajax Editor


©