Java Reference
In-Depth Information
alert("This link is going nowhere");
return false;
}
document.getElementById("someLink").onclick = linkClick;
</script>
</body>
</html>
Save this as
ch10_example3.html
.
First, you have the
<a/>
element, whose object's event you are connecting to. You'll notice there is
no mention of the event handler or the function within the attributes of the tag, but do notice that
it now has an
id
attribute. This is so that you can easily find the element in the document with the
getElementById()
method.
Next, you define the function
linkClick()
, much as you did previously. As before, you can return a
value indicating whether you want the normal action of that object to happen.
The connection is made between the object's event and the function on the final lines of script, as
shown in the following code:
document.getElementById("someLink").onclick = linkClick;
As you learned in the previous chapter, the
getElementById()
method finds the element with
the given
id
and returns the
a
object. You set this object's
onclick
property to reference your
function—this makes the connection between the object's event handler and your function. Note
that no parentheses are added after the function name. You are assigning the
linkClick
function
object to the element's
onclick
property, not executing
linkClick()
and assigning its return value
to
onclick
.
Take a moment and look back at
ch10_example2.html
. When you listened for the
click
event using
the
onclick
attribute, you had complete control over how
changeImg()
was called; you simply
called the function and passed it the
event
object.
But that's now an issue. Look again at the
onclick
property assignment:
document.getElementById("someLink").onclick = linkClick;
You no longer control how the event handler function is executed; the browser executes the function
for you. How then do you attain a reference to the
Event
? When an event triggers and an event
handler executes, the browser automatically passes an
Event
object to the handler function.
Displaying random Images with Object property Event handlers
trY it out
In this Try It Out, you rewrite
ch10_example2.html
to use the
onclick
property of the
img
objects.
Type in the following code:
<!DOCTYPE html>
<html lang="en">