Monday, March 21, 2005

Really basic event confusion

This is another no-brainer, but I still see this all the time:

function someEventHandler(e) {
    alert(e.type);
}

Works in Firefox and other Moz browsers. IE pops an error. Why? Because in IE browsers, the event (e) object is a property of the window, not a local argument passed to the handler. So e is undefined, in IE's view. To get around this, try:

function someEventHandler(e) {
    if (!e) e = window.event;
    alert(e.type);
}

The amusing thing about having to post this is I hear this question a lot from developers who are used to coding only for Firefox. How times change, eh?

3 Comments:

At 11:57 AM, Anonymous alan said...

Okay, this post had me feeling like a moron (or at least really confused) because I do this all the time in cross-browser scripts and have never had a problem. Confusion is not a state I enjoy being in, so I did a little experimenting and this is what I came up with (I even copied and pasted the event handler you defined in this post to make sure I was following you correctly):

If you assign the event handler directly with the 'onclick' attribute in a tag, it will fail in both IE and Firefox because 'e' is undefined.

If you assign the event handler to an object in script by setting its 'onclick' attribute to the event handler's name, it will fail in IE because e is undefined but work in Firefox.

If you assign the event handler to an object in script using 'attachEvent' or 'addEventListener' as appropriate (which is what I always do), it works in both browsers.

I'm not sure what to make of this other than feeling stupid for not knowing why the three methods produce such different results. I am a bit amazed that I've never been bitten by it (not that I remember, anyway). Yet another tidbit for my "you don't even know what you don't know" file, I guess.

 
At 5:49 AM, Blogger HiiFii Webservices said...

I liked you Blog so much,so i also wanted to show you some good resourses on the net.
Learn to earn 90000$/Month
For which you may also see my Personal Website
Here.
and for a Personal Education Career Tools
free Study Database.
This site is for seeing the
Hifi Electronics.
And this is for
World Class Gadgets

 
At 6:19 PM, Blogger satxxkenn said...

Cool blog - Check out my site if you need help finding a good low interest credit card. Credit Cards

 

Post a Comment

<< Home