Introduction

Event listeners are not the only way to handle events. Before event listeners where introduced in the DOM there was attributes in HTML and their respective properties on the elements.

Event Handlers

Event handlers can be added by either adding an attribute in the HTML source code or setting the property on the element in the DOM tree.

<button onclick="alert('Hello World')">Say it</button>

<script>
buttonElement.onclick = sayIt;
</script>

The problem

Once again the problem is that IE does not pass along the event object as the argument to the function that is supposed to handle the event. And since we cannot fix IE we have to make Mozilla work with the less powerful way of doing things by binding the event object to window.event.

The problem is where do we plug in the code to bind the event object? The solution is to do that during the capture phase of the event. Events start in the capturing phase, starting at the root of the document, going towards the node that caused the event to fire. Once it has reached that node the capture phase is over and the bubbling phase begins. In this phase the event traverses from the target node towards the root of the document tree. It is during this phase that old style event handlers are notified.

The solution

The solution is to capture the event at the root during the capture phase and at that point bind the event object to window.event.

The emulation

There is still a small problem left and that is that we have to add a listener to the document object for all types of event we want to support. This is not a really big deal but the page that wants to use this emulation needs to tell what type of events it should support.

function emulateEventHandlers(eventNames) {
   for (var i = 0; i < eventNames.length; i++) {	
      document.addEventListener(eventNames[i], function (e) {
         window.event = e;
      }, true); // using capture
   }
}

Usage

To allow Mozilla to access the event object as window.event in old style event handlers you need to include the ie emu file as well as call the method emulateEventHandlers with an array containing the types of the events you want to support.

<script type="text/javascript" src="ieemu.js"></script>
<script type="text/javascript">

if (moz) {
   emulateEventHandlers(["click", "mousemove"]);
}

</script>

Demo

Introduction
The power of JS
Event Listeners
Classic Event Handlers
Event Object
InnerHTML Model
Element Model
Document All Model
Current Style Model
???

Author: Erik Arvidsson