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.


/* Check to see if browser uses addEventListener or attachEvent */
	function addEvent(evnt,elem,func) {
		if(elem.addEventListener) {
		else if(elem.attachEvent) {
		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 *