Event handler properties (Definition)

Objects can have event handlers attached via property values.

From JavaScript version 1.1, you can attach event handlers by saving a reference to a function object in a property whose name is the same as the event.

If there is no handler defined then MSIE stores a reference to the null object in the event property of the Element object, while Netscape leaves the property undefined.

The property names must be all lower case even though the convention is to use mixed case when the event handlers are defined in HTML as tag attributes.

It is a useful thing to be able to define event handlers like this since mixing JavaScript and HTML in tag attributes is somewhat messy and can become more difficult to maintain.

A major benefit of this technique is that you can dynamically change the event handler associated with an object without changing the document's HTML. You might want to make the error handler more complex after repeated errors. Or you might want to reuse some objects and have form value checking change according to some user choices.

See also:Calling event handlers, Element.onevent