Difference between addEventListener and attachEvent
In JavaScript if you don't want to override and event but want to add one more listener to a specific event you need attach to that event. If you are using Chrome and Firefox addEventListener works fine. Nonetheless, if you are using any version of IE which is older than version 9, you need to attach to that event with attachEvent .
addEventListener example:
el.addEventListener("click", functionA, false)
attachEvent example:
el.attachEvent("onclick", functionA).
Notice that event names are different 'onclick' and 'click'.
Since attachEvent is deprecated, you can first check the addEventListener function availability on the browser and then use attachEvent as a fail safe scenario. (http://msdn.microsoft.com/en-us/library/ie/ms536343(v=vs.85).aspx)
if(el.addEventListener){
el.addEventListener("click", functionA, false)
}
else {
el.attachEvent("onclick", functionA)
}
Happy coding...
addEventListener example:
el.addEventListener("click", functionA, false)
attachEvent example:
el.attachEvent("onclick", functionA).
Notice that event names are different 'onclick' and 'click'.
Since attachEvent is deprecated, you can first check the addEventListener function availability on the browser and then use attachEvent as a fail safe scenario. (http://msdn.microsoft.com/en-us/library/ie/ms536343(v=vs.85).aspx)
if(el.addEventListener){
el.addEventListener("click", functionA, false)
}
else {
el.attachEvent("onclick", functionA)
}
Happy coding...
Comments