Java Reference
In-Depth Information
}
}
if (type == "click") {
alert("You clicked the mouse button at the X:"
+ e.clientX + " and Y:" + e.clientY + " coordinates");
}
}
document.attachEvent("onmouseover", handleEvent);
document.attachEvent("onmouseout", handleEvent);
document.attachEvent("onclick", handleEvent);
</script>
</body>
</html>
Save this as
ch10_example12.html
, and load it into old‐IE. It'll look and behave exactly like Example
8; the paragraph text will change to red and have an underline as you move your mouse pointer over the
paragraphs. When your mouse pointer leaves a paragraph, the text returns to the original state. When
you click your mouse, an
alert
box tells you the coordinates of where your mouse pointer was when
you clicked.
You assign the
handleEvent()
function to handle the
mouseover
,
mouseout
, and
click
events on the
document
object:
document.attachEvent("onmouseover", handleEvent);
document.attachEvent("onmouseout", handleEvent);
document.attachEvent("onclick", handleEvent);
When you cause any of these events to fire, the browser updates the
event
object and calls the
handleEvent()
function:
function handleEvent(e) {
var target = e.srcElement;
var type = e.type;
First, you want to get the target of the event (or in old‐IE speak, the source element), so initialize the
target
variable with the
event
object's
srcElement
property and the
type
variable with the
event
object's
type
property.
Next, you check if the event target has a
tagName
of
P
. If so, you determine what kind of event took
place by using the
type
variable:
if (target.tagName == "P") {
if (type == "mouseover") {
target.className = "underline";
} else if (type == "mouseout") {
target.className = "";
}
}
For
mouseover
events, you change the paragraph's CSS class to
underline
. If the event type is
mouseout
,
the element's
className
property is set to an empty string—returning the text to its original style.