Java Reference
In-Depth Information
function handle(e) {
alert(e.type);
}
</script>
Notice that
event
is passed to the
handle()
function in the
ondblclick
attribute. This
event
variable is special in that it is not defined anywhere; instead, it is an argument used only with event
handlers that are connected through HTML attributes. It passes a reference to the current event
object when the event fires.
If you ran the previous example, it would just tell you what kind of event raised your event‐handling
function. This might seem self‐evident in the preceding example, but if you had included the
following extra lines of code, any one of three elements could have raised the function:
<p ondblclick="handle(event)">Paragraph</p>
<h1 onclick="handle(event)">Heading 1</h1>
<span onmouseover="handle(event)">Special Text</span>
<script>
function handle(e) {
alert(e.type);
}
</script>
This makes the code much more useful. In general, you will use relatively few event handlers to
deal with any number of events, and you can use the event properties as a filter to determine what
type of event happened and what HTML element triggered it, so that you can treat each event
differently.
In the following example, you see that you can take different courses of action depending on what
type of event is returned:
<p ondblclick="handle(event)">Paragraph</p>
<h1 onclick="handle(event)">Heading 1</h1>
<span onmouseover="handle(event)">Special Text</span>
<script>
function handle(e) {
if (e.type == "mouseover") {
alert("You moved over the Special Text");
}
}
</script>
This code uses the
type
property to determine what type of event occurred. If users move their
mouse cursor over the
<span/>
element, an
alert
box tells them so.
You learn a lot more about the
Event
object later in the chapter, but for now, just know that it
exposes a property called
target
. This is the
target
of the event, the element object that received the
event. With this information, you can rewrite
ch10_example1.html
to use the more versatile
Event
object.