I'm trying to add a blur event to some form elements which will run some code for me. After the initial blur, I'm trying to remove the listener from that element so that it doesn't fire again.
The onblur event works fine, but for some reason the eventListener.remove never seems to fire, so blur doesn't get removed. Any ideas as to what I'm doing wrong?
UPDATED based on lincolnk's comments, but still NOT working in IE:
(function() {
var els = [document.getElementsByTagName('input'),
document.getElementsByTagName('select')],
eventListener = {
add: function(el, ev, fn) {
if (window.addEventListener) { // Standard
el.addEventListener(ev, fn, false);
} else if (window.attachEvent) { // IE
var iefn = function() { fn.call(el) };
el.attachEvent('on' + ev, iefn)
} else { return false };
},
remove: function(el, ev, fn) {
if (window.removeEventListener) { // Standard
el.removeEventListener(ev, fn, false)
} else if (window.detachEvent) { // IE
var iefn = function() { fn.call(el) };
el.detachEvent('on' + ev, iefn)
} else { return false };
}
},
wtFormTracker = function() {
console.log(this.name);
eventListener.remove(this, 'blur', wtFormTracker);
};
for (var i = 0, j = els.length; i < j; i++) {
for (var y = 0, z = els[i].length; y < z; y++) {
eventListener.add(els[i][y], 'blur', wtFormTracker);
}
}
})();
UPDATE: Fully operational in all browsers
(function() {
var els = [document.getElementsByTagName('input'),
document.getElementsByTagName('select')],
eventListener = {
add: function(el, ev, fn) {
if (window.addEventListener) { // Standard
el.addEventListener(ev, fn, false);
} else if (window.attachEvent) { // IE
el.attachEvent('on' + ev, fn)
} else { return false };
},
remove: function(el, ev, fn) {
if (window.removeEventListener) { // Standard
el.removeEventListener(ev, fn, false)
} else if (window.detachEvent) { // IE
el.detachEvent('on' + ev, fn)
} else { return false };
}
},
wtFormTracker = function(el) {
var target = el.target || el.srcElement;
console.log("'WT.ti','title-of-page','WT.ac', " + target.name);
eventListener.remove(target, 'blur', wtFormTracker);
};
for (var i = 0, j = els.length; i < j; i++) {
for (var y = 0, z = els[i].length; y < z; y++) {
eventListener.add(els[i][y], 'blur', wtFormTracker);
}
}
})();