Im trying to add a cross browser event listener to an element so i made my own function that detects weather the browser is IE or Firefox, then add the appropriate eventListener function to the element.
// CROSS-BROWSER ADD EVENT HELPER METHODS
function addCrossBrowserEventListener (elementName, eventName, functionName) {
// does the addEventListener function exist?
if(elementName.addEventListener) {
// yes - use it
elementName.addEventListener(eventName, functionName, false);
return true;
} else {
// otherwise use attachEvent for IE
elementName.attachEvent("on" + eventName, functionName);
return true;
}
}
var name = document.getElementById("name");
function nameLabel () {
name.innerHTML = "Welcome";
}
name.addCrossBrowserEventListener(name,"click", nameLabel);
but when i run the code inside Firefox i get a error message “name.addCrossBrowserEventListener is not a function”.
So I’m wondering is it possible to add custom functions to elements directly or is there any special way of doing it.
The reason why it’s returning undefined is because your function isn’t a prototype of the Function object, to my understanding you should simply be able to use the following.
// CROSS-BROWSER ADD EVENT HELPER METHODS
Function.prototype.addCrossBrowserEventListener(eventName, functionName) {
// does the addEventListener function exist?
if (this.addEventListener) {
// yes - use it
this.addEventListener(eventName, functionName, false);
return true;
} else {
// otherwise use attachEvent for IE
this.attachEvent("on" + eventName, functionName);
return true;
}
}
var name = document.getElementById("name");
function nameLabel() {
name.innerHTML = "Welcome";
}
name.addCrossBrowserEventListener("click", nameLabel);
There is still a major problem with using Microsoft’s attachEvent, and that is that the this keyword does not work properly.
It works properly in Internet Explorer when using traditional event assignments, such as el.onclick = …
But when using the attachEvent method, the this keyword instead refers to the window object, and is effectively broken.
You can get some information from the event object, but there can be major problems there too when the triggering element is different from the target element.
When someone else wrote an addEvent function that used attachEvent or addEventListener, the problems with attachEvent were delved into in this Quirksmode article on how addEvent is considered harmful
That inspired a war of sorts, where people tried all sorts of things to fix the problem, which resulted in a series of Rock Solid addEvent functions being created. One of which is Dustin Diaz’s rock-solid addEvent function.