If you’ve been developing web sites or apps for any length of time you’ve probably at least heard that HTML and JavaScript should be segregated. It’s such a good idea that the concept got it’s own fancy buzz term “Unobtrusive JavaScript”. The basic idea is that presentation, content, and behavior (oh my!) should be decoupled and replacable, which will make the code easier to maintain, enhance, overhaul or disable without causing it to implode.
But this is easy, right? You probably already have your JavaScript in an external JavaScript file where you have all of your functions defined. The onclick or onload attributes for your elements describe which functions defined in the external script should be called. …Wait a second, isn’t defining what happens when you click an element defining a behavior … what is behavior doing in HTML? This is where attachEvent comes into play.
The JScript method attachEvent allows you to attach events from the script – a decoupled, replaceable, external script. If you implement something like what is shown below you can set the onclick event handler of an element in your HTML to call doSomething().
element.attachEvent("onclick", doSomething);
This probably looks great in Internet Explorer but if you run it in FireFox, clicking on that same element will do nothing. This reason for this is that Firefox does not recognize JScript methods – it’s implementation of JavaScript is standards compliant (imagine that). Firefox, instead, recognizes attachEventListener for the same purpose. So, you are stuck with a method that works for Internet Explorer and a method that works everywhere else, but before you jump into the code and use the useragent to detect which browser is being used, consider checking the support of each feature and then use the feature that is supported. This is demonstrated in the code snippet below.
if (element.addEventListener) {
element.addEventListener("click", doSomething, null)
}
else if (element.attachEvent) {
element.attachEvent("onclick", doSomething);
}
Hope this helps and keep on bustin’.