This article is about a case where I needed to attach a “click” event to an anchor tag using JavaScript, and have it work with IE8 and up. The only reason for this is 30% of our users still use IE8. That is a large amount of users to just forget about. So I came up with an event handler that checks for the old IE “attachEvent” and “detachEvent”.

The first thing you need is an “addEvent” function to handle attaching an event to a DOM element.  The following JavaScript handles this:

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

Now we need a function to remove the event from the DOM element:

var removeEvent = function (element, eventType, handler) {
    if (element.removeEventListener) {
        element.removeEventListener(eventType, handler, false);
    } else if (element.detachEvent) {
        element.detachEvent('on' + eventType, handler);
    }
}

To use these functions we need to create a variable that holds the DOM element:

var anchor = document.getElementById('clickme');

Create a handler function to attach to our DOM element:

var handler = function (event) {
    console.log('clicked')
};

Then we just need to attach or detach the handler to the DOM element:

//Attach handler to DOM element
addEvent(anchor, 'click', handler);
//Detach the handler when not needed.
removeEvent(anchor, 'click', handler);

The “addEvent” and “removeEvent” functions can be placed in a separate .js file and loaded right before your closing body tag.  This allows you to use them in any other HTML file you need backwards compatibility with IE.

Hope everyone finds this useful.

Categories


Most Visited