Difference between AddEventListener and Attachevent javascript function

by Viper 24. June 2009 06:06

Even after so many years of javascript development, I hit my head into wall yesterday. I had some piece of code that needed to be executed on window load event. So being cross browser support freak, I had a check for addEventListener and attachEvent to makes sure that most of the browsers were covered. Yes, you must be thinking why i am not using libraries like jQuery. Simple answer is that in this release of the application I could not because of additional testing required. Following code should be something we all have seen at some point.


if (window.addEventListener){
  window.addEventListener('load', doWindowLoadVoodoo, false); 
} else if (window.attachEvent){
  window.attachEvent('onload', doWindowLoadVoodoo);
}

All of a sudden the application stopped working on >FireFox. As far I remembered i did not make any substantial changes to java script or any server side. After banging my head for some time, I decided to look at where I defined the above piece of code. On first look nothing looked out of place. When I looked closely, I was beating myself. Look at the code below.


if (window.addEventListener){
  window.addEventListener('onload', doWindowLoadVoodoo, false); 
} else if (window.attachEvent){
  window.attachEvent('onload', doWindowLoadVoodoo);
}

If you have not noticed, I modified the line of code that was attaching to load event using addEventListener. The correct syntax is to simply specify name of the event and not the event handler name. So in this case, event is load and not onload. Where as attachEvent requires you to specify event handler name which in this case is onload. This is very subtle mistake that one can make.

Views: 1342

Tags:

Javascript

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.6.1
Theme by Naveen Kohli

Recent

By Categories