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 !