Java Reference
In-Depth Information
myButton.value = "Mouse Goes Down";
}
myButton.addEventListener("mousedown", myButtonMousedown);
myButton.addEventListener("mouseup", myButtonMouseup);
</script>
</body>
</html>
Save this page as
ch11 _ example3.html
and load it into your browser. If you click the button with your
left mouse button and keep it held down, you'll see the text on the button change to “Mouse Goes
Down.” As soon as you release the button, the text changes to “Mouse Goes Up.”
In the body of the page, you define a button called
myButton
within a form called
form1
:
<form action="" name="form1">
<input type="button" name="myButton" value="Mouse goes up" />
</form>
Your JavaScript code retrieves this
Button
object from the document and stores it in the
myButton
variable, and you register event listeners for the
mouseup
and
mousedown
events.
The
myButtonMouseup()
and
myButtonMousedown()
functions handle those events, respectively. Each
function consists of just a single line of code, in which you use the
value
property of the
Button
object
to change the text that is displayed on the button's face.
An important point to note is that events like
mouseup
and
mousedown
are triggered only when the
mouse pointer is actually over the element in question. For example, if you click and hold down the
mouse button over your button, then move the mouse away from the button before releasing the mouse
button, you'll find that the
mouseup
event does not fire and the text on the button's face does not change.
In this instance it would be the
document
object's
mouseup
event that would fire, if you'd connected any
code to it.
Don't forget that, like all form element objects, the
Button
object also has the
focus
and
blur
events,
though they are rarely used in the context of buttons.
Two additional button types are the Submit and Reset buttons. You define these buttons just as you
do a standard button, except that the
type
attribute of the
<input>
tag is set to
submit
or
reset
rather than to
button
. For example, the Submit and Reset buttons in Figure 11-4 were created using
the following code:
<input type="submit" value="Submit" name="submit1" />
<input type="reset" value="Reset" name="reset1" />
These buttons have special purposes, which are not related to script.
When the Submit button is clicked, the form data from the form that the button is inside gets sent to
the server automatically, without the need for any script.
When the Reset button is clicked, all the elements in a form are cleared and returned to their default
values (the values they had when the page was first loaded).