Cross-Browser Event Handlers

    Event are certain actions performed either by the users or by the browser itself , like click , load or mouseover . There are four event handlers in JavaScript : HTML event handler , DOM level 0 event handler , DOM level 2 event handler and IE event handler .

    First , HTML event handler : Every HTML element can be added a event which is linked to a action . Like : 

<input type=”button” value=”Click Me” οnclick=”alert(‘Clicked’)” />
    Or like : 
<script type=”text/javascript”> function showMessage(){
alert(“Hello world!”); }
</script>
<input type=”button” value=”Click Me” οnclick=”showMessage()” />
    Second , DOM level 0 event handler : In JS , you can get the element and then add a action to a element's event . Like : 

var myButton = document.getElementById(“myButton”);
myButton.onclick = function(){
	alert(“Clicked”); 
};
    Third : DOM level 2 event handler : You can add a event to a element using the addEventListener() function , and you also can overwrite it by using it twice . Like : 
var btn = document.getElementById(“myBtn”); 
btn.addEventListener(“click”, function(){
	alert(this.id); }, false);
btn.addEventListener(“click”, function(){
	alert(“Hello world!”);
}, false);
    Fourth : IE event handler . You should use the attachEvent() function to do it . Like : 
var btn = document.getElementById(“myBtn”);
btn.attachEvent(“onclick”, function(){
    alert(“Clicked”);
});
    But how we use them to cross browser ? In fact , we can define a object named EventUtil which has some functions , like addHandler or removeHandler ... 
var EventUtil = {
	addHandler: function(element, type, handler){
		if (element.addEventListener){
		    element.addEventListener(type, handler, false);
	    } else if (element.attachEvent){
		    element.attachEvent('on' + type, handler);
	    } else {
		    element['on' + type] = handler;
		}
	},
	removeHandler: function(element, type, handler){
		if (element.removeEventListener){
			element.removeEventListener(type, handler, false);
		} else if (element.detachEvent){
			element.detachEvent('on' + type, handler);
		} else {
			element['on' + type] = null;
		}
	}
};
    So there it is , I hope it will help you . Good night ! 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值