Event listener/Attach Event check function

Earlier versions of Internet Explorer use attachEvent instead of the customary addEventListener function.
Here is a way of checking and using the correct function depending on the browser your code is being used in.

Function

/* Check to see if browser uses addEventListener or attachEvent */
	function addEvent(evnt,elem,func) {
		if(elem.addEventListener) {
	        elem.addEventListener(evnt,func,false);
		}
		else if(elem.attachEvent) {
			elem.attachEvent('on'+evnt,func);
		}
		else {
			elem['on'+evnt] = func;
		}
	}

Use it like this

        var elem = document.getElementById('myElem');
        addEvent('click', elem, funcForClick);

Share this

Leave a Reply

Your email address will not be published. Required fields are marked *