The Javascript DOM21. Cross Browser Event Processing |
|
Join the DiscussionMore of this FeatureIntroduction Collections getElementById Accessing Properties Changing Styles innerHTML getElementsByTagName getElementsByClassName removeChild createElement and createTextNode appendChild insertBefore replaceChild createDocumentFragment Table Methods Event Handlers Attaching Event Handlers DOM Event Processing Event Listeners attachEvent 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. |

