addEventListener and attachEvent for IE8

addEventListener and attachEvent for IE8. Getting to that stage where your almost out of IE8’s reach but it just keeps pulling you back in?

I too have had instances where I’ve tried to make the breakaway but have been pulled back. One such is trying to use addEventListener more, however if you are in the world of IE8 (all the way down to IE5 too) then you are in harsh luck. However we can create a nice simple check to fall back to attachEvent (IE5-8). Add the following to your Javascript:

function addMyEvent(element,eventType,handler) {
 if (element.addEventListener)
     element.addEventListener (eventType,handler,false);
 else if (element.attachEvent)
     element.attachEvent ('on'+eventType,handler); 
}

// which can be used like so:
jeeves = document.getElementById('jeevesID');

addMyEvent(jeeves,'click',functionToRun);

functionToRun = function(){
     console.log('Damn you sir');
}

notice in the attachEvent fall back the need to add: ‘on’+eventType. This is IE5-8’s way of doing it e.g. onClick onHover etc. If anyone knows the reason why that was the case I’d love to know.




Random Posts