Javascript, the DOM, addEventListener and attachEvent

Apr 12 2005

While scripting the voting widget for the post-May-1st CSS Reboot site, I had some problems with attaching events cross-browser, caused almost entirely by some incorrect code posted on another site.

Because inline event handlers are, like, so 1999, I am using a function to attach the mouseOver and mouseOut events to a series of images; and due to Internet Explorer’s non-support of the standard addEventListener method, I am branching the code to detect support of the available options:

if (el.addEventListener) {
el.addEventListener ("mouseover",myFunction,false);
el.addEventListener ("mouseout",myFunction,false);
} else if (el.attachEvent) {
el.attachEvent ("onmouseover",myFunction);
el.attachEvent ("onmouseout",myFunction);
} else {
el.onmouseover = myFunction;
el.onmouseout = myFunction;
}

The problem was caused by the example I was working from using the wrong syntax for the attachEvent method – it missed out the leading “on” from the first argument (the name of the event).

Eventually I worked out what the problem was (with the help of this handy cross-browser attachEvent function), but it just goes to show you can’t take everything you read on the internet at face value – even the geeks get it wrong sometimes!

Filed under: Javascript.

Digg this article

Bookmark this article with del.icio.us

Previously: Idiot's Guide to Bathroom Tiling

Next: Make your own Conservative election poster


Comments

Jordan Arentsen
1385 days ago
Which technique did you finally decide to use? The code you provided, or the attachEvent function from the link?
#1
Matthew Pennell
1385 days ago
Jordan: I now use an all-purpose Event object – you can find it in use on this page
#2
adix
1287 days ago

Interesting.
But, there is a difference between IE5.0 and the other IE’s.

#3