Event Handling in Javascript IE and Mozilla

As scripted sites can be very useful to users and EventHandlers in Javascript are a nice feature if you have a more complex site, we want to create a Method so EventHandlers will be recognized in Internet Explorer as well as in Mozilla browser and function as intended.
1 answer

Working Javascript event handling or IE and Mozilla

The most important step is to retrieve the browser version in Javascript. When we know with which Browser we are dealing we can differ between the necessary commands which have to be executed. The following code shows the differences between IE 8 (and older) and Mozilla


function createSafeListener(toField, listenerType, functionToDo) {
var appName = navigator.appName;
if (appName == 'Microsoft Internet Explorer') {
toField.attachEvent('on' + listenerType, functionToDo);
} else {
toField.addEventListener(listenerType, functionToDo, false);
}
}

This function lets call it "createSafeListener" accepts 3 parameters

  • toField - The field where the event should be attached to
  • listenerType - The type of listener we need (i.e. onChange, onClick, ...)
  • functionToDo - The function which should be executed when the event fires
    • The differences we see is that IE uses attachEvent instead of addEventListener. The second difference is IE expects something as "onChange", while Mozilla only needs "change" and moreover Mozilla has an additional parameter which i dont explain in details here (false is sufficient in most cases).

      When we have this function we can use it easily for implementation i.e.:


      var noField = document.getElementById('other_1_count');
      createSafeListener(noField,'change',function() { setCount(this); });
      createSafeListener(noField,'keyup',function() { setCount(this); });

      You would think we are done now .. but not yet there is still another problem we have to consider. When the desired function is call, we possibly need access to the corresponding field from which it was called, there is also again a difference between IE and Mozilla, see below


      var appName = navigator.appName;
      if (appName == 'Microsoft Internet Explorer') {
      if (window.event.srcElement) {
      elem = window.event.srcElement;
      }
      }

      In case of IE the parameter "this" of setCount(this) will be null, so we have to check again on which browser we are working and use the correct function of IE which is window.event.srcElement

Taggings: