Java Reference
In-Depth Information
What Are Events?
Events occur when something in particular happens. For example, the user clicking on the page, clicking
on a hyperlink, or moving the mouse pointer over some text all cause events to occur. Another example,
which is used quite frequently, is the load event for the page: the window raises (or fi res) a notifi cation
when the page is completely loaded in the browser.
Why should you be interested in events?
Take as an example the situation in which you want to make a menu pop up when the user clicks any-
where in your web page. Assuming that you can write a function that will make the pop-up menu
appear, how do you know when to make it appear, or in other words, when to call the function? You
somehow need to intercept the event of the user clicking in the document, and make sure your function
is called when that event occurs.
To do this, you need to use something called an event handler or listener. You associate this with the
code that you want to execute when the event occurs. This provides you with a way of intercepting
events and making your code execute when they have occurred. You will fi nd that adding an event
handler to your code is often known as “connecting your code to the event.” It's a bit like setting an
alarm clock — you set the clock to make a ringing noise when a certain event happens. With alarm
clocks, the event is when a certain time is reached.
Connecting Code to Events
Chapter 5 introduced objects defi ned by their methods and properties. However, objects also have
events associated with them. This was not mentioned before, because native JavaScript objects do not
have these events, but the objects of the BOM (and Document Object Model, or DOM, which you'll
see in Chapter 12) do.
Event handlers are made up of the word on and the event that they will handle. For example, the click
event has the onclick event handler, and the load event has the onload event handler.
A number of ways exist to connect your code to an event using event handlers. In this chapter you'll
look at two of the easiest ways to add events, ways that have been around a very long time and are sup-
ported even by older browsers, as well as by current ones. In Chapter 12 you're going to look at newer
and standards-friendly ways of adding events.
Handling Events via HTML Attributes
The fi rst and most common method is to add the event handler's name and the code you want to exe-
cute to the HTML element's attributes.
Let's create a simple HTML page with a single hyperlink, given by the element <a/>. Associated to this
element is the a object. One of the events the a object has is the click event. The click event fi res, not
surprisingly, when the user clicks the hyperlink.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
Search WWH ::




Custom Search