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)

    el.addEventListener("click", functionA, false)
else {
    el.attachEvent("onclick", functionA)

Happy coding...


Popular posts from this blog

Space Character Problem on IE 6, 7, and 8

Configure hosts File in Android

AWS encryption chart (SSE-S3 vs SSE-KMS vs SSE-C)