JAVASCRIPT: Internet Explorer’s attachEvent breaks ‘this’
First of all, let me just say that I love jQuery. It makes Javascript development so much faster. I’m sure that Prototype is just as easy for those that use that daily, but I prefer jQuery. And before you ask… Yes, I learned both.
That having been said, there are some applications where I cannot use a Javascript library and I need to use the (longer) Javascript methods. There’s nothing wrong with this - in fact, I find that I always learn something new. Such was the case today.
I decided that I would attach some events using the addEventListener function. I had always either used the older method of attaching events or some helper library. So I checked out the spec on MDC and saw that Internet Explorer had its own version of this function called attachEvent. I hate how Internet Explorer does things like this. There are standards for a reason, you know.
Anyway, I wrote a simple function that would apply the event, but it was not working in Internet Explorer. So I started debugging the issue.
“Is the event being attached?” - Yes
Is the event being attached to the right object?” - Yes
Can I alert some text in the event function?” - Yes… odd.
Here’s my function:
1 2 3 4 5 6 7 8 9 10 11 12 | addEvent(this.container, 'mouseover', function(){ this.className = 'over'; }); addEvent = function(el, event, func) { if (el.addEventListener) { el.addEventListener(event, func, false); } else if (el.attachEvent) { el.attachEvent('on'+event, func); } else { el['on'+event] = func; } }; |
It turns out that Internet Explorer doesn’t pass the ‘this’ object to the event function. ‘this’ is this instance should be the object that had the event attached.
It’s no shock to people that know me that I hate Internet Explorer. I even sell T-shirts declaring that fact. But this is just stupid.
Why did Microsoft have to implement their own version of addEventListener? Why did they have to implement it so horribly that it doesn’t return ‘this’?
I ended up writing a workaround that just used the older method of applying the event to the object. Here’s the finished version:
1 2 3 4 5 6 7 8 | addEvent = function(el, event, func) { if (el.addEventListener) { el.addEventListener(event, func, false); } else { el['on'+event] = func; } }; |
It’s really just adding insult to injury, since the only reason I had to write this function is because Internet Explorer doesn’t handle the CSS :hover pseudo-class for DIV elements.
Anyone want a T-shirt?