Javascript Events Fixes

January 20, 2012 No Comments

Here is a fix for Javascript event that fixed two important problems:

  • Fix the scope of event handlers added with Internet Explorer’s attachEvent method (code taken from Yui Library)
  • Add support to mouseenter and mouseleave events

To use just paste on a Javascript file and use the function as you need it.

/*
 * Add Javascript events: support mouseenter and mouseleave and fix scope of event handlers
 * @function addEvent(obj, evnt, fn, useCapture)
 * 	@param obj:documentElement - a single element in a document
 * 	@param evnt:string - event name
 * 	@param fn:function - function to call on event
 * 	@param useCapture:boolean - useCapture indicates if the user wishes to initiate capture
 */
function addEvent(obj, evnt, fn, useCapture){
	if(typeof obj.attachEvent != 'undefined'){ // ie7 ie8 fix
		// utils for attachEvent
		function getEvent(e, boundEl){
			var ev = e || window.event;
		    if (!ev) {
		        var c = this.getEvent.caller;
		        while (c) {
		            ev = c.arguments[0];
		            if (ev && Event == ev.constructor) {
		                break;
		            }
		            c = c.caller;
		        }
		    }
		    return ev;
		}
		var wrappedFn = function(e) {
	        return fn.call(obj, getEvent(e, obj));
	    };
		// core for attachEvent
		obj.attachEvent("on"+evnt, wrappedFn);
	}else{
		// utils for addEventListener
		function mouseEnter(fn){
			return function(evnt){
				var relTarget = evnt.relatedTarget;
				if(this == relTarget || isAChildOf(this, relTarget)){return;}
				fn.call(obj, evnt);
			}
		};
		function isAChildOf(parent, child){
			if(parent == child){return false;}
			while(child && child !== parent){child = child.parentNode;}
			return child == parent;
		};
		// core for addEventListener
		if(evnt == 'mouseenter'){
			obj.addEventListener('mouseover', mouseEnter(fn), useCapture);
		}else if(evnt == 'mouseleave'){
			obj.addEventListener('mouseout', mouseEnter(fn), useCapture);
		}else{
			obj.addEventListener(evnt, fn, useCapture);
		}
	}
}

Comments

Leave a Reply