Java Reference
In-Depth Information
<form action=”“ name=”form1”>
<input type=”button” name=”myButton” value=”Button clicked 0 times”
onclick=”myButton_onclick()“ />
</form>
</body>
</html>
Save this page as ch7_examp2.htm . If you load this page into your browser, you will see a button with
“Button clicked 0 times” on it. If you repeatedly press this button, you will see the number of button
clicks recorded on the text of the button.
You start the script block in the head of the page by defi ning a global variable, accessible anywhere
inside your page, called numberOfClicks. You record the number of times the button has been clicked
in this variable and use this information to update the button's text.
The other piece of code in the script block is the defi nition of the function myButton_onclick() . This
function is connected to the onclick event handler in the <input/> element in the body of the page.
This element is for a button element called myButton and is contained within a form called form1 .
<form action=”“ name=”form1”>
<input type=”button” name=”myButton” value=”Button clicked 0 times”
onclick=”myButton_onclick()“ />
</form>
Let's look at the myButton_onclick() function a little more closely. First, the function increments the
value of the variable numberOfClicks by one.
function myButton_onclick()
{
numberOfClicks++;
Next, you update the text on the button face using the Button object's value property.
document.form1.myButton.value = “Button clicked “ +
numberOfClicks + “ times”;
}
The function in this example is specifi c to this form and button, rather than a generic function you'll
use in other situations. Therefore, the code in this example refers to the form and button directly using
document.form1.myButton. Remember the document object holds all the elements in a page, includ-
ing the <form/> element, and that the button is embedded inside your form.
Try It Out onmouseup and onmousedown
Two less commonly used events supported by the Button object are the mousedown and mouseup
events. You can see these two events in action in the next example.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 7: Example 3</title>
<script type=”text/javascript”>
Search WWH ::




Custom Search