1. Home
  2. Computing & Technology
  3. JavaScript

The Javascript DOM

21. Cross Browser Event Processing

clr gif

Since Internet Explorer uses its own proprietary method of processing events rather than the standard event listener processing, we need a way of being able to test for which of these two methods that a particular browser supports. We can do this by creating a function that will use feature sensing to select the supported method and use that. We can also have the code add a regular onevent handler for those antiquated browsers that don't support either of the other methods. This last isn't perfect as each added event will automatically overwrite any previously added entries in that instance but since those antiquated browsers (such as the no longer supported Mac version of IE) don't support tyhe code for updating event handlers to replace their content, this is the best that we can do.

function addEvent(el, eType, fn, uC) {
if (el.addEventListener) {
el.addEventListener(eType, fn, uC);
return true;
} else if (el.attachEvent) {
return el.attachEvent('on' + eType, fn);
} else {
el['on' + eType] = fn;
}
}

With this function in place we can now add an event handler to an identified tag in our page using code like this:

addEvent(
document.getElementByID('idname'),
'click',idnameClicked,false);

This example will detect a mouse click on the field having an id of idname and will call the idnameClicked() function.

To be fully cross browser we also need a way to handle the propogation and default processing options as well. The following two functions will do this for us:

function stopProp(e) {
if (e && e.stopPropogation) e.stopPropogation();
else if (window.event && window.event.cancelBubble)
window.event.cancelBubble = true;
}
function stopDef(e) {
if (e &&e.preventDefault) e.preventDefault();
else if (window.event && window.event.returnValue)
window.eventReturnValue = false;
}

Unfortunately, there is not much that we can do about older browsers that have only partly implemented this functionality but hopefully this will soon cease to be an issue as the newer browsers all support this code and so only those people who have failed to keep their browser at least reasonably up to date will be affected.

Explore JavaScript

More from About.com

  1. Home
  2. Computing & Technology
  3. JavaScript
  4. Animation & Effects
  5. Document Object Model
  6. Cross Browser Event Processing

©2008 About.com, a part of The New York Times Company.

All rights reserved.