The event handlers are standardized in DOM level 2 interface. They are used to allow JavaScript to register different event handlers on HTML DOM objects such as elements, document, window object…etc. The methods addEventListener() and removeEventListener() are defined and can be used on all nodes. The addEventListener() method adds an event listener to an element, while the removeEventListener() method can be used to remove these same event listeners or handlers. The advantage of those methods is that multiple handlers can be added to an event and also multiple events can be added to an element. These event handlers are supported in IE9, Firefox, Safari, Chrome, and Opera.

Syntax for event listeners

addEventListener(event, function, useCapture);

removeEventListener(event, function, useCapture);

where:

Example of adding and removing event listeners

The example above adds a mouseover and mouseout events to a paragraph. The mouseout event has an anonymous function. The first listener can be removed by clicking on the button. However the second listener cannot be removed as the function is anonymous. Passing that function as a parameter to removeEventListener() does not work.

The attachEvent() and detachEvent() methods

The Internet Explorer implements listener methods as attachEvent() and detachEvent(). These methods accept the event's name and the event's handler function. Since versions before IE8 supported only bubbling, third argument is omitted.

Syntax for attachEvent() and detachEvent() methods

document.getElementById(“element”).attachEvent(“event“, handler);

document.getElementById(“element”).detachEvent(“event“, handler);

 

›› go to examples ››