Categories:
Partners

Netscape 4 and Netscape 6 event models

Tutorial written and contributed by Jason Davis, moderator of the JK Forum. Edited/ minor additions by JK. Please see tutorial footnote for additional/bio info on author.

This tutorial looks at the now legacy event model of Netscape 4, and more applicable, that of Netscape 6 as well (Firefox shares a very similar event model as NS6's). Many developers struggle with Netscape 4 and 6's seemingly lacking event model, where there is no explicit event object to work with. In IE, there is window.event, which provides detailed information regarding the occurring event (ie: where the mouse was, what element was clicked on etc). Well, there are in fact ways to compensate for the lack of this "miracle object" in Netscape, and in this tutorial, we'll see how!

Netscape 4+ does support window.event (well, indirectly)!

Let's look at the simple example of embedding an event handler inside a link:

<a href="file.html" onclick="doSomething()">

inside doSomething(), you can get the event info in IE via window.event, but what many don't realize is you can accomplish the equivalent in NS. Netscape places event handler functions into a wrapper function, and passes the event object as an argument to it. So, how do we get to it?

#1: Explicitly passing an "event" parameter

We can allow functions attached to an event in Netscape to access the event object by passing in event as a parameter. For example:

<a href="file.html" onclick="doSomething(event)">

event is a variable in the onclick() function namespace, or scope. doSomething() is inside that scope as well, so we pass the object event into it. Then you can reference event inside doSomething().

#2: By invoking arguments.callee.caller.arguments[0]

So far so good, but what if you don't want to use any event argument, as you want to pass your own argument without messing it up in Internet Explorer?

In JavaScript1.2+, the code arguments.callee.caller allows you to reference the containing wrapper function, which the event object is passed into. By taking advantage of this fact, we can rewrite doSomething() to retrieve the event object in Netscape directly inside the function:

function doSomething() {
// arguments.callee.caller.arguments[0] references the event object
alert(arguments.callee.caller.arguments[0].type) // "click"
}

Voila, we got the event without passing a single argument, now, cross browser:

function doSomething() {
var theEvent=window.event || arguments.callee.caller.arguments[0];
// rest of script
}

Pretty cool uh?