Java Reference
In-Depth Information
The most common user‐based events are mouse events, and rightly so. The primary way users
interact with their computers is with the mouse, but that's starting to change as more and more
people own touch‐enabled devices.
The main focus of this chapter is to teach you how to listen for events, and it does so primarily with
mouse events. In the next chapter, you use some keyboard events to interact with forms.
ConneCting Code to events
Browsers have been around for quite some time, and as you can guess, the way in which we listen for
events has evolved over the years. But even with the many changes the JavaScript community has seen
over the years, the old ways of listening for events are still supported and useful in certain situations.
Chapter 5 introduced objects defined 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 browser object model (BOM) and document object model (DOM) do.
You can connect your code to an event in three ways:
Assigning HTML attributes
Assigning an object's special properties
Calling an object's special methods
handling events via html attributes
In this section you create a simple HTML page with a single hyperlink, given by the element <a/> .
Associated with this element is the a object, and one of the events the a object has is the click
event. The click event fires, not surprisingly, when the user clicks the hyperlink. Feel free to follow
along; open your text editor and type the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Connecting Events Using HTML Attributes</title>
</head>
<body>
<a href="somepage.html">Click Me</a>
</body>
</html>
As it stands, this page does nothing a normal hyperlink doesn't do. You click it, and it navigates the
window to another page, called somepage.html , which would need to be created. There's been no
event handler added to the link—yet!
As mentioned earlier, one way of connecting the event to your code is to add it directly to the opening
tag of the element object whose event you are capturing. In this case, it's the click event of the a
object, as defined by the <a/> element. On clicking the link, you want to capture the event and connect
 
Search WWH ::




Custom Search