Java Reference
In-Depth Information
<p>This is paragraph 3.</p>
<script>
function handleEvent(e) {
var target = e.target;
var type = e.type;
if (target.tagName == "P") {
if (type == "mouseover") {
target.className = "underline";
} else if (type == "mouseout") {
target.className = "";
}
}
if (type == "click") {
alert("You clicked the mouse button at the X:"
+ e.clientX + " and Y:" + e.clientY + " coordinates");
}
}
document.addEventListener("mouseover", handleEvent);
document.addEventListener("mouseout", handleEvent);
document.addEventListener("click", handleEvent);
</script>
</body>
</html>
Save this as
ch10_example8.html
and run it in your
browser. When you move your mouse over one of the
paragraphs, you'll notice its text changes color to red
and it becomes underlined. Click anywhere in the page,
and you'll see an
alert
box like Figure 10-3.
Now click OK, move the pointer in the browser
window, and click again. A different result appears.
figure 10-3
This example is consistent with the event‐handling
behavior: The browser waits for an event, and every
time that event occurs it calls the corresponding function. It will continue to wait for the event until
you exit the browser or that particular web page. In this example, you assign event handlers for the
mouseover
,
mouseout
, and
click
events on the
document
object:
document.addEventListener("mouseover", handleEvent);
document.addEventListener("mouseout", handleEvent);
document.addEventListener("click", handleEvent);
One function,
handleEvent()
, handles all three of these events.
Whenever any of these events fire, the
handleClick()
function is raised and a new
MouseEvent
object
is generated. Remember that
MouseEvent
objects give you access to
Event
object properties as well as
MouseEvent
object properties, and you use some of them in this example.