attaching events to nodes in Javascript
For you hard-core javascript junkies that attach your own nodes to the DOM, I recently ran into a problem with attaching events to the nodes I was generating. It would work fine in Firefox, but not in Internet Explorer. Here's the (psuedo) code that I was using
Like I said, this worked fine in Firefox, but not in IE. I evenetually found out that IE does not support adding events through the setAttribute method. Instead, you need to use an IE-specific command called attachEvent instead. Since this command only exists in IE, the way I wrote the code so that it works in both IE and Firefox is like so
The important thing to note about attachEvent is that you pass the actual function to it, not the name of the function as with setAtttribute. An additional thing to note is that attachEvent invokes calls as global function, so in the context of the function called this refers to the window object, not the object to which the event was attached like in setAttribute. Phew, IE sure makes this hard!
var newElement = document.createElement('input');
newElement.setAttribute('onclick', 'someFunction()');
Like I said, this worked fine in Firefox, but not in IE. I evenetually found out that IE does not support adding events through the setAttribute method. Instead, you need to use an IE-specific command called attachEvent instead. Since this command only exists in IE, the way I wrote the code so that it works in both IE and Firefox is like so
var newElement = document.createElement('input');
if ( newElement.attachEvent ) {
// This code gets executed by IE
newElement.attachEvent('onclick', someFunction);
} else {
// Other (sane) browsers execute this code
newElement.setAttribute('onclick', 'someFunction()');
}
The important thing to note about attachEvent is that you pass the actual function to it, not the name of the function as with setAtttribute. An additional thing to note is that attachEvent invokes calls as global function, so in the context of the function called this refers to the window object, not the object to which the event was attached like in setAttribute. Phew, IE sure makes this hard!
| Rating: | no ratings, 0 total Votes |
| Categories: | javascript web programming internet explorer |
| Added: | on Aug 18, 2008 at 11:23 am |
| Added By: | an anonymous user |

