Java Reference
In-Depth Information
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 type=”text/javascript”>
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 fi lter 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 type=”text/javascript”>
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 the user moused over
the <span/> element, then an alert box tells them so.
Accessing event information is relatively straightforward if you're using HTML attributes to assign
event handlers. Thankfully, accessing event data when assigning event handlers using JavaScript objects'
properties are even more straightforward: the browser automatically passes the event object to the
handling function when the event fi res. Consider the following code:
<p id=”p”>Paragraph</p>
<h1 id=”h1”>Heading 1</h1>
<span id=”span”>Special Text</span>
<script type=”text/javascript”>
function handle(e)
{
if (e.type == “mouseover”)
Search WWH ::




Custom Search