↑
Main Page
Event properties
Using the
mouseover
and
mouseout
events is a popular way to change the appearance of something on
the page, such as an image. This is a very simple technique, but is still very frequently used:
<img src=”image1.gif” onmouseover=”this.src=’image2.gif’”
onmouseout=”this.src=’image1’.gif” />
In this code snippet, the
onmouseover
and
onmouseout
event handlers are filled with just a single line.
Notice the use of the
this
object to change the
src
property of the image? This is one of the hidden
truths of event handlers: An event handler is considered a method of the object on which it is assigned.
Therefore, the
this
object can be used to access the event target (which is helpful, in this instance,
because it avoids a browser detect). When the
mouseover
event fires, the image’s
src
property is set to
image2.gif
, which presumably is different from
image1.gif
; when the
mouseout
event fires, the
src
property is set back to
image1.gif
.
Event properties
For each mouse event, the following properties are filled in on the
event
object:
?
Coordinate properties (such as
clientX
and
clientY
, and so on)
?
The
type
property
?
The
target
(DOM) or
srcElement
(IE) property
?
The
shiftKey
,
ctrlKey
,
altKey
, and
metaKey
(DOM) properties
?
The
button
property (only on
mousedown
,
mousemove
,
mouseout
,
mouseover
, and
mouseup
events)
Each of these properties gives some information about the mouse event that just occurred. You are
already familiar with the
type
property, but if the other properties are added into event handling, you
begin to get a more complete picture of the event that occurred:
<html>
<head>
<title>Mouse Events Example</title>
<script type=”text/javascript”>
function handleEvent(oEvent) {
var oTextbox = document.getElementById(“txt1”);
oTextbox.value += “\n>” + oEvent.type;
oTextbox.value += “\n target is “ + (oEvent.target ||
oEvent.srcElement).id;
oTextbox.value += “\n at (“ + oEvent.clientX + “,” +
oEvent.clientY + “) in the client”;
oTextbox.value += “\n at (“ + oEvent.screenX + “,” +
oEvent.screenY + “) on the screen”;
oTextbox.value += “\n button down is “ + oEvent.button;
var arrKeys = [];
if (oEvent.shiftKey) {
arrKeys.push(“Shift”);
}
281
All about Events
12_579088 ch09.qxd 3/28/05 11:39 AM Page 281
Free JavaScript Editor
Ajax Editor
©
→