I’ve been working on a Javascript library, one with basic functionality.
I’m fairly new to Javascript, and am weaning myself off of jQuery, mainly for the sake of self-improvement.
My goal is to have a javascript library compatible with IE 8+, so I’m looking for browser-specific gotchas.
One specific problem is my event module, which doesn’t seem to work when I try to add multiple events to one selector in Firefox 4.
Here’s the module in question:
And the rest of the library is at github: https://github.com/timw4mail/kis-js/blob/master/kis.js
(function(){
var attach, remove, add_remove, e;
if(document.addEventListener)
{
attach = function(sel, event, callback)
{
if(sel.addEventListener)
{
sel.addEventListener(event, callback, false);
}
};
remove = function(sel, event, callback)
{
if(sel.removeEventListener)
{
sel.removeEventListener(event, callback, false);
}
};
}
else
{
attach = function(sel, event, callback)
{
if(sel.attachEvent)
{
sel.attachEvent("on"+event, callback);
}
};
remove = function(sel, event, callback)
{
if(sel.detachEvent)
{
sel.detachEvent("on"+event, callback);
}
};
}
add_remove = function (sel, event, callback, add)
{
var i,len;
if(!sel)
{
return false;
}
//Get the DOM object if you give me a selector string
if(typeof sel === "string")
{
sel = $(sel);
}
//Multiple events? Run recursively!
event = event.split(" ");
if(event.length > 1)
{
console.log(event);
len = event.length;
for(i=0;i<len;i++)
{
add_remove(sel, event[i], callback, add);
}
return;
}
//Check for multiple DOM objects
if(sel.length > 1)
{
len = sel.length;
for(i=0;i<len;i++)
{
(add === true)
? attach(sel[i], event, callback)
: remove(sel[i], event, callback);
}
}
else
{
(add === true)
? attach(sel, event, callback)
: remove(sel, event, callback);
}
};
e = {
add: function(sel, event, callback)
{
add_remove(sel, event, callback, true);
},
remove: function(sel, event, callback)
{
add_remove(sel, event, callback, false);
}
};
window.$_.event = e;
}());
Okay, after a while of searching, I found the problem is not with your library at all, but is with your test code. The problem is that
innerTextdoesn’t work in Firefox 4. A version of your test code, updated to useinnerHTMLinstead ofinnerText, works perfectly.Also, your library has some other compatibility issues that I thought I should point out:
and
should have matching parameters for their third argument.
Quote from MDC wiki:
And also, another compatibility thing (for IE8 or below):
attachEventexpects you to have “on” before the event name, like so:element.attachEvent("onmouseover", function(){...});