February 2, 2000 - Event Handler Definition
February 2, 2000 Event Handler Definition Tips: February 2000
Yehuda Shiran, Ph.D.
|
- HTML attribute
- Property assignment
Consider the following form definition:
<FORM NAME="myForm">
<INPUT TYPE="button" NAME="myButton" VALUE="click here">
</FORM>
When you click the button, nothing happens because no script or function is attached to its click event. For instance, you could associate it with a function that generates an alert dialog box by placing an onClick event handler script in the body of the tag:
<SCRIPT LANGUAGE="JavaScript">
<!--
function myAlert() {
alert("Thank you for clicking the button.");
}
// -->
</SCRIPT>
<FORM NAME="myForm">
<INPUT TYPE="button" NAME="myButton"
VALUE="click here" onClick="myAlert()">
</FORM>
Another way to associate a function with a specific event is to assign its reference to the object's event handler property:
<SCRIPT LANGUAGE="JavaScript">
<!--
function myAlert() {
alert("Thank you for clicking the button.");
}
// -->
</SCRIPT>
<FORM NAME="myForm">
<INPUT TYPE="button" NAME="myButton" VALUE="click here">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!--
document.myForm.myButton.onclick = myAlert;
// -->
</SCRIPT>
And yet another variation on the same theme is defining the event handler function in-line. We chose a different event handler to demonstrate the usage of this
:
<FORM NAME="myForm">
<INPUT TYPE="button" NAME="myButton" VALUE="click here">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!--
document.myForm.myButton.onclick = function() {
this.style.border = "2px buttonhighlight inset";
}
// -->
</SCRIPT>
Learn more about event handling in The Internet Explorer Event Model.