168Part IIIDocument Objects ReferenceObject Event HandlersAnevent handlerspecifies how (Managed web hosting)
168Part IIIDocument Objects ReferenceObject Event HandlersAnevent handlerspecifies how an object reacts to an event that is triggered by a useraction (for example, a button click) or a browser action (for example, the completion of adocument load). Going back to the earliest JavaScript-enabled browser, event handlerswere defined inside HTML tags as extra attributes. They included the name of the attribute, followed by an equal sign (working as an assignment operator) and a string containing thescript statement(s) or function(s) to execute when the event occurs (see Chapter 5). Eventhandlers also have other forms. In NN3+ and IE4+, event handlers have correspondingmethods for their objects and every event handler is a property of its object. Event handlers as methodsConsider a button object whose sole event handler is onclick. This means whenever the but- ton receives a click event, the button triggers the JavaScript expression or function callassigned to that event handler in the button s HTML definition: Normally, that click event is the result of a user physically clicking the button in the page. InNN3+ and IE4+, you can also trigger the event handler with a script by calling the event han- dler as if it were a method of the object: document.formName.clicker.onclick(); Invoking an event handler this way is different from using a method to simulate the physicalaction denoted by the event. For example, imagine a page containing three simple text fields. One of those fields has an onfocusevent handler defined for it. Physically tabbing to or click- ing in that field brings focus to the field and thereby triggers its onfocusevent handler. If thefield does not have focus, a button can invoke that field s onfocusevent handler by referenc- ing it as a method: document.formName.fieldName.onfocus(); This scripted action does not bring physical focus to the field. The field s own focus() method, however, does that under script control. A byproduct of an event handler s capability to act like a method is that you can define theaction of an event handler by defining a function with the event handler s name. For example, instead of specifying an onloadevent handler in a document s
tag, you can define afunction like this: function onload() { statements} This capability is particularly helpful if you want event handler actions confined to a scriptrunning in NN3, IE4, or later. Your scripts don t require special traps for Navigator 2 orInternet Explorer 3. Event handlers as propertiesAlthough event handlers are commonly defined in an object s HTML tag, you also have thepower in NN3+ and IE4+ to assign or change an event handler just like you assign or changethe property of an object. The value of an event handler property looks like a function defini- tion. For example, given this HTML definition: