Team LiB
Previous Section Next Section

Binding Events to Elements

There are two ways to bind an event to an element so that it can be used: by using tag attributes or assigning an event handler to an object property. Event handler as tag attribute is the type of event handler you will use most often. Event handlers as tag attributes are useful for capturing events generated by HTML elements. Event handlers as object properties are only used with objects such as the built-in JavaScript window and document objects.

Event Handlers as Tag Attributes

The most common, and easiest, way to bind an event to an element is through the element's tag attributes. The examples earlier in this chapter mostly used this type of event binding. In the calculator example, the Equal key, (=), had the following event binding:

<input type="button" value=" = "
        onClick="JavaScript: document.CalcForm.Display.value=
                  calculate( document.CalcForm.Display.value );">

This means that every time this button (onClick) is pressed, the code that is assigned to the onClick parameter is executed.

It is important that you specify the language that you are using so that the interpreter knows how to execute the code. You do this by preceding the JavaScript code with "JavaScript:"

The keyword this comes into play again when using events. In the following example, this is referencing the element in which the event handler is located—the input tag:

<html>
  <head>
    <title>
        JavaScript Professional Projects -
          Event Binding via Tag Attributes
    </title>
 
    <script language="JavaScript">

    <!--
      function upper( field )
      {
        field.value = field.value.toUpperCase();
      }
    // -->
    </script>
   </head>

   <body>

     <center>
       <font size=6>JavaScript Professional Projects</font><br>
       <font size=4>Chapter 6: Event Binding via Tag Attributes</font>
     </center>

     <br><br>

     <form>
       <b>Input text here:&nbsp; </b>
       <input type="text" size="20" onKeyUp="JavaScript: upper(this);">
     </form>

   </body>
</html>

This example makes use of the onClick event to convert the contents of a text field into uppercase letters by passing a reference to itself to the function upper().

Event Handlers as Object Properties

In Navigator 3 and Internet Explorer 4 and later, there is another way to bind event handlers— by binding it to an object property. For every event handler that an object supports, there is a property with the same name in all lowercase letters. You can bind the event handler to the object by using the assignment operator (=), just like you would for any other kind of object property.

<html>
  <head>
    <title>
        JavaScript Professional Projects - Binding Events

    </title>

    <script language="JavaScript">
    <!--

      function load()
      {
         alert("onLoad event");
      }

      function unload()
      {
         alert("onUnload event")
      }

      window.onload = load;
      window.onunload = unload;
    // -->
    </script>
  </head>
 
  <body>
 
   <center>
     <font size=6>JavaScript Professional Projects</font><br>
     <font size=4>Chapter 3: Binding Events</font>
   </center>

   <br><br>
   <br><br>

   <a href="http://www.yahoo.com/">Some other page.</a>
  </body>
</html>

You can create an event handler function just as you would any other function. To make it an event handler for an object, simply assign it to the appropriate object property, as in the example above. This technique skirts the problem older browsers have with event binding as tag attributes. Tag attributes are not recognized as valid HTML in older browsers. One disadvantage of this approach is that parameters cannot be passed to the event handler functions.

Event Handler Return Values

One big advantage of using event handlers as tag attributes is that the return value from the handler function can often be used to modify the default actions of the browser. Here is an example to demonstrate this concept:

<html>
   <head>
     <title>
         JavaScript Professional Projects - Event Handler Return Values
     </title>
 
     <script language="JavaScript">
     <!--
       function changeBGColor( color )
       {
         document.bgColor = color;
         return( false );
       }
     // -->
     </script>
   </head>

   <body>
     <center>
       <font size=6>JavaScript Professional Projects</font><br>
       <font size=4>Chapter 6: Event Handler Return Values</font>
     </center>

     <br><br>
     <br><br>

     Make the background 
       <a href="unknown_page.html"
          onClick="return( changeBGColor( 'red' ) );">red</a>!

     <br><br>
   
     Make the background
       <a href="unknown_page.html"
             onClick="return( changeBGColor( 'blue' ) );">blue</a>!
 
     <br><br>

     Make the background 
       <a href="unknown_page.html"
             onClick="return( changeBGColor( 'green' ) );">green</a>!

     <br><br>

     Make the background 
       <a href="unknown_page.html"
              onClick="return( changeBGColor( 'yellow' ) );">yellow</a>!

     <br><br>

     Make the background 
       <a href="unknown_page.html"
              onClick="return( changeBGColor( 'purple' ) );">purple</a>!

       <br><br>

       Make the background 
         <a href="unknown_page.html"
                onClick="return( changeBGColor( 'white' ) );">white</a>!
    
   </body>
</html>

The event handlers are always called before the HTML commands are executed. In the example above, the link href "unknown_page.html" does not exist, but that really doesn't matter. Because the event handler function returns the value false, the Web page interprets that as an error and does not follow the link at all. This trick becomes especially useful when validating forms:

<form method="POST" onSubmit="return( validate( this ) );">

This form will only submit if the event handler function validate (which checks the validity of each form element) returns a true value.


Team LiB
Previous Section Next Section