The usage of both is similar, though both take on a slightly different syntax for the event parameter:
addEventListener (mdn reference):
Supported by all major browsers (FF, Chrome, Edge)
obj.addEventListener('click', callback, false);
function callback(){ /* do stuff */ }
Events list for addEventListener.
attachEvent (msdn reference):
Supported by IE 5-8*
obj.attachEvent('onclick', callback);
function callback(){ /* do stuff */ }
Events list for attachEvent.
Arguments
For both of the methods the arguments are as follows:
- Is the event type.
- Is the function to call once the event has been triggered.
- (
addEventListeneronly) If true, indicates that the user wishes to initiate capture.
Explanation
Both methods are used to achieve the same goal of attaching an event to an element.
The difference being is that attachEvent can only be used on older trident rendering engines ( IE5+ IE5-8*) and addEventListener is a W3 standard that is implemented in the majority of other browsers (FF, Webkit, Opera, IE9+).
For solid cross browser event support including normalizations that you won’t get with the Diaz solution use a framework.
*IE9-10 support both methods, for backwards compatibility.
Thanks to Luke Puplett for pointing out that attachEvent has been removed from IE11.
Minimal cross browser implementation
As Smitty recommended you can use this Dustin Diaz addEvent implementation for a solid cross browser implementation without the use of a framework:
function addEvent(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
}
else if (obj.attachEvent) {
obj["e"+type+fn] = fn;
obj[type+fn] = function() {obj["e"+type+fn](window.event);}
obj.attachEvent("on"+type, obj[type+fn]);
}
else {
obj["on"+type] = obj["e"+type+fn];
}
}
addEvent( document, 'click', function (e) {
console.log( 'document click' )
})