JavaScript: The Definitive Guide

25.91. Element.attachEvent( ): register an event handler

IE 4:

25.91.1. Synopsis

void attachEvent(String type, Function listener);

25.91.1.1. Arguments

type

The type of event for which the event listener is to be invoked, with a leading "on" prefix. For example, "onload", "onclick", or "onmousedown".

listener

The event listener function that is invoked when an event of the specified type is dispatched to this element. This function is not passed any arguments but can obtain the Event object from the event property of the Window object.

25.91.2. Description

This method is an IE-specific event registration method. It serves the same purpose as the standard addEventListener( ) method (which IE does not support) but is different from that function in several important ways:

  • Since the IE event model does not support event capturing, attachEvent( ) and detachEvent( ) expect only two arguments: the event type and the handler function.

  • The event-handler names passed to the IE methods should include the "on" prefix. For example, use "onclick" with attachEvent( ) instead of "click" for addEventListener( ).

  • Functions registered with attachEvent( ) are invoked with no Event object argument. Instead, they must read the event property of the Window object.

  • Functions registered with attachEvent( ) are invoked as global functions, rather than as methods of the document element on which the event occurred. That is, when an event handler registered with attachEvent( ) executes, the this keyword refers to the Window object, not to the event's target element.

  • attachEvent( ) allows the same event-handler function to be registered more than once. When an event of the specified type occurs, the registered function is invoked as many times as it is registered.

This method is also defined by, and works analogously on, the Document and Window objects.

25.91.3. See Also

Element.addEventListener( ), Event; Chapter 17

Категории