Java Reference
In-Depth Information
<head>
<title>Connecting Events Using HTML Attributes</title>
</head>
<body>
<a href=”somepage.htm” name=”linkSomePage”>
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.htm , which would need to be created. There's been no event
handler added to the link — yet!
As mentioned earlier, one very common and easy 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 defi ned by the <a/> element. On clicking the link, you want to capture
the event and connect 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 have executed
when the event occurs.
Let's rewrite the opening <a> tag to do this as follows:
<a href=”somepage.htm” name=”linkSomePage” onclick=”alert('You Clicked?')”>
Click Me
</a>
This code adds onclick=”alert('You Clicked?')” to the defi nition 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 defi ned in the href attribute.
This is fi ne 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 defi ne the function you want to execute and call it in the onclick code. Let's
do that now.
<!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”>
<head>
<title>Connecting Events using HTML Attributes</title>
</head>
<body>
<script type=”text/javascript”>
function linkSomePage_onclick()
{
alert('You Clicked?');
return true;
}
</script>
Search WWH ::




Custom Search