Java Reference
In-Depth Information
listener on the target on which it's called. You call it on a target/element object, as you see in the
following example. Type in the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 10, Example 5</title>
</head>
<body>
<a id="someLink" href="somepage.html">
Click Me
</a>
<script>
var link = document.getElementById("someLink");
link.addEventListener("click", function (e) {
alert("This link is going nowhere");
e.preventDefault();
});
</script>
</body>
</html>
Save this as
ch10_example5.html
. This is a re‐creation of
ch10_example3.html
, but it uses
the standard event model
application programming interface
(API), which is a set of objects,
properties, and methods, to register an event listener and prevent the default action of a link from
occurring.
The first line of JavaScript retrieves the element that has an
id
of
someLink
, and stores it in the
link
variable. You then call the
addEventListener()
method and pass it two arguments. The first is the
name of the event without the
"on"
prefix. In this example, an event listener is registered for the
click
event.
The second argument is the function that executes when the event occurs. The previous code uses
an anonymous function, a common pattern that you'll see very often, but it's more useful to pass a
declared function, like this:
function linkClick() {
alert("This link is going nowhere");
e.preventDefault();
}
link.addEventListener("click", linkClick);
Using a declared function lets you reuse it for multiple event listeners, as you see in the next exercise.
But first, notice that
linkClick()
no longer returns
false
; instead, it calls the
preventDefault()
method on the
Event
object. This is the standard way that you prevent the default action from
occurring.