Since I have been thinking about my image gallery project, I have a lot
of things to study for the best work.
Today, I read the article from http://www.quirksmode.org, it mentions to
“addEventListener” method in Javascript.
addEventListener is the method which used to add an event to an element.
Suppose if you want to add the alert event when user clicks on an element,
just do like this.
element.addEventListener('click', function(){ alert("Something"); }, true);
So, if you click on an element, alert window will appear.
But in IE, you can’t use “addEventListener” to add an event to element, it uses
“attachEvent” to add an event.
In IE, the above code won’t work, use the below code.
element.attachEvent('onclick', function(){ alert("Something"); });
It’s complicated to write code for both IE and other browsers right?
So, I have written the simple function to add an event to an element
that works on both.
And here is my function.
var zEvent = {
'add' : function(el, eventName, fn){
if(navigator.appName == "Microsoft Internet Explorer") el.attachEvent('on' + eventName, fn);
else el.addEventListener(eventName, fn, true);
},
'remove' : function(el, eventName, fn){
if(navigator.appName == "Microsoft Internet Explorer") el.detachEvent('on' + eventName, fn);
else el.removeEventListener(eventName, fn, false);
}
};
This is how to use it.
zEvent.add(element, 'click', function(){ alert("Something"); });
Hope this useful for you.
Thanks.