The Cross-Browser Event Model: The Event Object - Doc JavaScript | WebReference

The Cross-Browser Event Model: The Event Object - Doc JavaScript

The Event Object

The event object holds various information about the event, such as the type of event, the exact position of the mouse cursor when it occurred, and the object under the cursor at that instant. The event object is described in Column 9 and Column 10.

The event object is implemented differently in both browsers. Internet Explorer 4.0x features this object as a property of the window object, so it is specified as window.event. The window object is the default one, so it is not necessary. Thus, the word event simply refers to the event object.

In Navigator 4.0x, the event object is handed to the event processing function as an argument if the event handler is specified via the property assignment approach. But if it is specified as an HTML attribute, you must explicitly provide the event object to the function. The function that processes the event must have a parameter in order to refer to the event object.

A cross-browser event processing function must feature a parameter, so it can handle Navigator 4.0x's event object. It must also utilize an object detection routine, so it knows how to refer to the event object, depending on the browser. The following example shows how to write a function that is executed when you move the mouse:

var nav4 = window.Event ? true : false;
function processMovements(e) {
  if (nav4) {
    // use the "e" reference
  } else {
    // use the "event" (or "window.event") reference
if (nav4)
document.onmousemove = processMovements;
// -->

The first statement is probably the most important one. It checks if the browser is Navigator 4.0x by determining if it supports the window.Event object. Notice the capital "E" letter. Internet Explorer 4.0x supports the window.event object (which exists only when an event occurs), while Navigator 4.0x supports the window.Event object. Even though the difference is only the case of a single character, it is extremely important. If the browser is Navigator 4.0x (or above), the nav4 variable evaluates to true, and the function accesses the event object by referring to the parameter e. In all other cases (Internet Explorer 4.0x), the function should access the event object by specifying its name: event. When an event handler is defined as an HTML attribute, and the event object is explicitly handed to the function, it is possible to refer to the function's parameter in both browsers. We'll discuss this later in the column.

Created: January 13, 1998
Revised: January 13, 1998