Tuesday, 29 June 2010

Cross Browser addEventListener

So I got to thinking about why I hade loads of onclick elements written into my code and how it really didn't help the readability and purity of the X/HTML code so I decided to look at addEventListener which is something I've seen lots on comp.lang.javascript but has always worried me ever so slightly. Anyway, it's not all that hard really, you just do something like var helloP = document.getElementById("helloWorld"); helloP.addEventListener('click', helloWorld, false ); and then add a function like this: function helloWorld(e){ alert("Hello World");}

It's not all that hard except that you need to appreciate that Internet Explorer doesn't implement it that is!

Instead Internet Explorer uses attachEvent and it behaves in a different manner. Say we wanted to get the ID of the element that was clicked in the above example. In most browsers we'd use an alert like this: alert("Hello World, you pressed the paragraph with the id of \""+e.target.id+"\"."); but internet explorer will get all confused and say that it doesn't understand target... it does understand srcElement though. At the beginning of our script we can check whether the helloWorld function can't understand target by asking if(!e.target) and it it doesn't then e.target will become srcElement thus: if(!e.target){e.target = e.srcElement;}

If course we've still got to add the listener in the first place so we could replace addEventListener with a generic function which handles all the browser problems and I found one here, but I didn't like the shorthand of the variables it was using so refactored them to this:

function addEvent(element, type, listener, useCapture) {
  if (element.addEventListener) {
    element.addEventListener(type, listener, useCapture);
    return true;
  } else if (element.attachEvent) {
    return element.attachEvent('on' + type, listener);
  } else {
    element['on' + type] = listener;
  }
}

So we've a cross browser way of adding listeners and a cross browser way of handling the result of the listener, cool ehh? If only IE would stop being such a pig!

Edit: It would seem that that isn’t all that’s needed, after reading this article on quirksmode I may well have to do some more work if I'm after anything other than the ID of the element clicked!

No comments:

Post a Comment