HTML and CSS Reference
In-Depth Information
13.8 The Scripting Model for Handling Events
We have been using event handlers like onClick , onSubmit , and onMouseOver , through-
out this text. So far, this chapter has described in detail all of the different event handlers
and how to use them as inline HTML attributes. Inline event handling is the oldest and
simplest way to handle events and is browser compatible. The following example uses
the onClick handler as an attribute of the button element. When the user clicks the but-
ton, the function movePosition() will be called.
<input type="button" value="move text"
onClick="movePosition() "/>
But using this type of handler violates the principle of separation of the layers; that
is, the separation of markup/presentation from behavior/ JavaScript. To solve this prob-
lem, we can handle events within the JavaScript code itself. All of the HTML attributes
used as event handlers can also be used as DOM properties. These properties can be used
in JavaScript to simulate the event that they are named for. If, for example, you want to
trigger a window event, JavaScript views the window as an object and any event associ-
ated with it as a property. If you want to use the onload event with the window object,
you would say window.onload . The main difference is that unlike using HTML attributes,
which take a string value, a function reference is assigned to an event handler. All Java-
Script event properties must be in lowercase, such as window.onload or window.ununload .
(The event handlers, used as HTML attributes, are not case sensitive, so ONUNLOAD ,
onUnLoad , and onunload are all acceptable.)
Here's an example:
window.unload=some_function;
13.8.1 Getting a Reference to the Object
To assign an event property to an object, JavaScript will need a reference to the object.
For example, if the click event is to be triggered when the user clicks a button, then Java-
Script will need to use a reference to the button. By assigning an id to the HTML button,
JavaScript can use the DOM's getElementById( ) method to get the reference it needs.
In the HTML part of the document:
input type button id=”button1” >
In the JavaScript script:
var b 1 =document.getElementById("button1");
Now b1 in the script is a reference to “button1” from the HTML document.
After JavaScript has a reference to the HTML element, the name of the event, such as
click or onmouseover can be used as a property:
b1.click
b1.mouseover
 
 
 
Search WWH ::




Custom Search