February 11, 2000 - Loading Event Handlers | WebReference

February 11, 2000 - Loading Event Handlers

Yehuda Shiran February 11, 2000
Loading Event Handlers
Tips: February 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

What's wrong with the following script?

<SCRIPT LANGUAGE="JavaScript">
<!--
function clicked() {
  alert("You clicked a button.");
}
document.myForm.myButton.onclick = clicked;
// -->
</SCRIPT>
<FORM NAME="myForm">
<INPUT TYPE="button" VALUE="click here" NAME="myButton">
</FORM>

This script generates a JavaScript error because it accesses a property of the document.myForm object before it's actually created. You may only assign a function reference to an event handler after its corresponding element has been created. One way to solve this problem is to revert the script-element order:

<FORM NAME="myForm">
<INPUT TYPE="button" VALUE="click here" NAME="myButton">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!--
function clicked() {
  alert("You clicked a button.");
}
document.myForm.myButton.onclick = clicked;
// -->
</SCRIPT>

A better (and safer) way to solve this issue is to define all functions in the document's <HEAD>...</HEAD> portion. Then assign a function to the event handler in a separate script, after the element's HTML code, or in a function that's called from the onLoad event handler. The following HTML documents demonstrate both techniques:

<!-- first technique -->
<HTML>
<HEAD>
<TITLE>Hello</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function clicked() {
  alert("You clicked a button.");
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myForm">
<INPUT TYPE="button" VALUE="click here" NAME="myButton">
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!--
document.myForm.myButton.onclick = clicked;
// -->
</SCRIPT>
</BODY>
</HTML>

<!-- second technique -->
<HTML>
<HEAD>
<TITLE>Hello</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function defineEvents() {
  // this works because the onLoad event handler
  // is called after the entire page has loaded
  document.myForm.myButton.onclick = clicked;
}
function clicked() {
  alert("You clicked a button.");
}
// -->
</SCRIPT>
</HEAD>
<BODY onLoad="defineEvents()">
<FORM NAME="myForm">
<INPUT TYPE="button" VALUE="click here" NAME="myButton">
</FORM>
</BODY>
</HTML>

Learn more about Netscape Navigator's event model in Column 9, The Navigator Event Model.