Exception Handling in JavaScript: Addressing Browser Incompatibilities
Not all browsers handle all code the same way. Differences can be addressed with JavaScript exceptions. These may not be the best way under all circumstances, but you'll find it worthwhile to examine this approach.
Exception Handling in JavaScript: Addressing Browser Incompatibilities - Proprietary event handlers: implementing browser-independent event handling (Page 4 of 5 )
One of the most requested features for the upcoming version of Internet Explorer is full support for the W3CDOMstandard “addEventListener()” method, which unfortunately is not implemented by Microsoft’s current browsers. Since Internet Explorer exposes its own “attachEvent()” method for tying events to objects, browser-independent event handling is very often achieved through sniffing functions, which use the proper event handling method, according to the browser that the script is executing on.
A typical script that deals with both event handlers may be written like this:
// regular Event Handler assignation var obj=document.getElementsByTagName('div')[0]; if(!obj){alert('Failed to get object!')}; if(obj.addEventListener){ // browser is Firefox, Netscape, etc. // use addEventListener() method obj.addEventListener("click",processEvent,false); } else if(obj.attachEvent){ // browser is Internet Explorer // use attachEvent() method obj.attachEvent('onclick',processEvent); } else { alert('Failed to add event handler'); }
As you can see, the above fragment of code uses some checking lines to determine what handling method will be attached to a regular <div> element, in order to call the “processEvent()” function when the element is clicked on. Given that, this function might be defined as simply as this:
function processEvent(){ alert('Event handler successfully attached!'); }
Using this technique, it’s possible to encapsulate the whole code into a generic function that solves internally the described incompatibilities and attaches events to objects as transparently as possible. In this case, I’d like to deliberately maintain the code out of wrapping functions though, so you can study it and decide the best approach to be taken.
For most developers, the above example is extremely simple and the code is pretty self explanatory. Certainly, the only thing worth considering is that similar results can be obtained with exceptions. Keeping in mind the same logic that I applied to creating XMLHTTP objects, it’s possible to solve browser differences when working with event handlers. So, the next step will consist of demonstrating an alternative method to assign events to objects, this time using exceptions.