Registering Event Handlers
There are two basic ways to register event handlers. The first,
from the early days of the Web, is to set a property on the object or
document element that is the event target. The second, newer and more
general, technique is to pass the handler to a method of the object or
element. To complicate matters, there are two versions of each
technique. You can set an event handler property in JavaScript code,
or for document elements, you can set the corresponding attribute
directly in HTML. For handler registration by method invocation, there
is a standard method, named addEventListener()
, that is supported by all
browsers except IE8 and before, and a different method, named attach
Event()
, for all versions of IE
before IE9.
Setting Event Handler Properties
The simplest way to register an event handler is by setting a
property of the event target to the desired event handler function.
By convention, event handler properties have names that consist of
the word “on” followed by the event name: onclick
, onchange
, onload
, onmouseover
, and so on. Note that these
property names are case sensitive and are written in all lowercase,
even when the event type (such as “readystatechange” consists of
multiple words. Here are two example event handler
registrations:
// Set the onload property of the Window object to a function.
// The function is the event handler: it is invoked when the document loads.
window
.
onload
=
function
()
{
// Look up a <form> element
var
elt
=
document ...
Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.