Java Reference
In-Depth Information
it to your code. You need to add the event handler, in this case
onclick
, as an attribute to the opening
<a>
tag. You set the value of the attribute to the code you want to execute when the event occurs.
Rewrite the opening
<a>
tag to do this as follows:
<a href="somepage.html" onclick="alert('You clicked?')">Click Me</a>
This code adds
onclick="alert('You Clicked?')"
to the definition of the opening
<a>
tag. Now,
when the link is clicked, you see an
alert
box. After this, the hyperlink does its usual stuff and
takes you to the page defined in the
href
attribute.
This is fine if you have only one line of code to connect to the event handler, but what if you want a
number of lines to execute when the link is clicked?
Well, all you need to do is define the function you want to execute and call it in the
onclick
code.
Do that now:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Connecting Events Using HTML Attributes</title>
</head>
<body>
<a href="somepage.html" onclick="return linkClick()">Click Me</a>
<script>
function linkClick() {
alert("You Clicked?");
return true;
}
</script>
</body>
</html>
Within the script block, you have created a standard function. The
onclick
attribute is now
connected to some code that calls the function
linkClick()
. Therefore, when the user clicks the
hyperlink, this function will be executed.
You'll also see that the function returns a value,
true
in this case. Also, where you define your
onclick
attribute, you return the return value of the function by using the
return
statement before
the function name. Why do this?
The value returned by
onclick="return linkClick()"
is used by JavaScript to decide whether
the normal action of the link—that is, going to a new page—should occur. If you return
true
, the
action continues, and you go to
somepage.html
. If you return
false
, the normal chain of events
(that is, going to
somepage.html
) does not happen. You say that the action associated with the event
is canceled. Try changing the function to this:
function linkClick() {
alert("This link is going nowhere");
return false;
}