IE, W3C and Event Handling…

Problem with JScript (Miscroft’s EcmaScript implementation) and the behavior of event registering.The recommendation, of the W3C, for register an event using EcmaScript is the use of the method addEventListener(..); implemented by all the browsers except by IE, instead you can use attachEvent(..). But if you try to use this function to register an event, think that you can’t use the keyword ‘this’ inside the event. This is because Microsoft implements a poor event handler; only works with one global event. And the keyword ‘this’ references to the window, global, object instead to the object that fires the event. This behavior is a bug that occurs since version 5.5.The only way to work properly with events in JScript using the keyword ‘this’ to refer the object that fires the object, is that you register the event without the function attachEvent(..). And Internet Explorer knows how to refer the object that fires the event.Example:

– This doesn’t work

1
2
3
4
5
var img1 = document.createElement("img");
img1.attachEvent("onclick", function () {
	if ( DoSomething(this.getAttribute("attribute1"), this.getAttribute("attribute1")) )
		return true;
});

– This works

1
2
3
4
5
var img1 = document.createElement("img");
img1.onclick = function() {
	if ( DoSomething(this.getAttribute("attribute1"), this.getAttribute("attribute1")) )
		return true;
});

Conclusion; if you work with the W3C recommendations in mind and Microsoft’s Technologies: don’t apply the recommendations.Happy coding!

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>