This tutorial covers four different approaches to assigning event handlers to DOM elements. We describe the differences between the approaches and provide guidance in choosing among them.
We use a basic form to show how functions can access elements and properties when handlers are attached using the following approaches:
- Assigning functions to event handler properties.
- Using the modern event model:
- Using the modern event model and including support for Internet Explorer 8 and earlier using the
- Including event handler attributes in HTML markup.
How to Choose? Weighing the Pros and Cons
Or maybe you lean toward the event handlers in HTML approach. Perhaps it seems simpler, but it is not considered good practice these days to mix markup and behavior.
If you wish to support older versions of Internet Explorer, the event handler property assignment approach might be the most convenient. It is supported by all browsers fairly consistently.
One drawback: assigning a function to an event handler property overwrites previous assignments. Although this can be a major problem with common events on window or document, it would generally be less problematic with forms.
Function Differences for Each Approach
The modern event model automatically passes a reference to the
event object. So does the property assignment approach, except in older versions of Internet Explorer where a reference would be obtained through the window object.
The modern event model and the property assignment approach also both make
this available inside the function to refer to the object to which the function was attached (a form, form element, or other DOM element). However, when using the modern event model and
attachEvent for older versions of Internet Explorer, extra work is required to obtain a reference to the object by way of
event. This example gives details.
When you include a function call in an event handler attribute, you can pass arguments. You can pass
this to refer to the object to which the handler is attached. You can pass
event, but you would need a minor code branch inside the handler function for older versions of Internet Explorer.
The event handler function will in some cases need to prevent the default action of an event: for example, navigation onclick of a link, or the submission of a form onsubmit if there are problems with form entries. Older approaches use
return false. The modern event model uses the