Handling events with the DOM - Part III - Determining the type of event: the "type" property (Page 3 of 7 )
To determine the type of event generated, we use the "type" property. We might easily write a function to detect the type the event. Say we want to display an alert box telling us what type of event was detected. For Nestcape6+ or Mozilla, the code looks like this:
And we might call the function (i.e. when the page is loaded) with the statement:
For the above example, the alert box will display "load", since we’re invoking the function with an "onload" event handler. In a IE environment, if we wish to know the type of event, the function should be rewritten in the following way:
Doing so, we’re obtaining the same results as the example given for Netscape and Mozilla. As we can see, it’s tremendously tedious to write a function for each browser type. So, the two above functions might be recoded in a cross-browser fashion, to deal with the different event models. Our final function looks like this:
Now, we’ve checked internally the existence of an event object. If there’s no such object, we’re using IE, so we access instead the "window.event" object. Just invoking the function through several event handlers will display "click", "load", "keypress", and so forth according to the event that fired the function. In order to simplify future examples, we’ll make use of the handy cross-browser version for accomplishing the common tasks inherent to a Web application. Our next objective is to determine the target of the event.