What's the problem of this piece of JavaScript code?
- by Yousui
Hi guys,
The following piece of JavaScript code is a cross browser way to add/remove event handler. It will save a deleting method as a property of an HTML element object. Now it works well in FireFox but not in IE6. I can't find out why so I came here for help. Great thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>pop</title>
</head>
<body>
<input type="text" name="input1" id="input1" value="" />
<div id="result">
</div>
<div id="result2" style="width:200px;height:100px;border:1px solid red;">
</div>
<button id="stop" name="stop">click me</button><button id="stop2" name="stop2">click me</button>
<script type="text/javascript" charset="utf-8">
function handler(e){
e = e || window.event;
var key_code = e.keyCode || e.charCode || e.which,
source = e.srcElement || e.target;
document.getElementById("result").innerHTML = "" + key_code;
}
function handler2(e){
e = e || window.event;
var key_code = e.keyCode || e.charCode || e.which,
source = e.srcElement || e.target;
document.getElementById("result2").innerHTML = e.button;
}
function add_event(o, event_type, callback, capture){
o = typeof o === "string" ? document.getElementById(o) : o;
if(document.addEventListener){
add_event = function(o, event_type, callback, capture){
o = typeof o === "string" ? document.getElementById(o) : o;
capture = typeof(capture) === "undefined" ? false : true;
o.addEventListener(event_type, callback, capture);
o.removes = o.removes || {};
o.removes[event_type] = function(){
o.removeEventListener(event_type, callback, capture);
};
if(!o.remove_event){
o.remove_event = function(type){
if(typeof type === "undefined"){
return;
}
o.removes[type]();
}
}
}
}else if(document.attachEvent){
add_event = function(o, event_type, callback, capture){
o = typeof o === "string" ? document.getElementById(o) : o;
capture = typeof(capture) === "undefined" ? false : true;
o.attachEvent(event_type, callback);
o.removes = o.removes || {};
o.removes[event_type] = function(){
o.detachEvent(event_type, callback);
}
if(!o.remove_event){
o.remove_event = function(type){
if(typeof type === "undefined"){
return;
}
o.removes[type]();
}
}
}
}
add_event(o, event_type, callback, capture);
}
add_event("input1", "keyup", handler);
add_event("input1", "click", handler2);
add_event("stop", "click", function(){
document.getElementById("input1").remove_event("keyup");
});
add_event("stop2", "click", function(){
document.getElementById("input1").remove_event("click");
});
</script>
</body>
</html>