[thelist] unobtrusive JS: adding events with parameters?

Christian Heilmann codepo8 at gmail.com
Thu Jan 12 09:35:54 CST 2006


>
> I'm using Scott Andrew's faithful addEvent() method[1] to add an event to some images at load time. My init function has this clause:

The issue with scott andrew's addEvent is that it doesn't retain the
"this", that is why there was a code competition to replace it.

http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html

As this one still has issues in Safari, I tend to use another method
to find the element that was activated called getTarget and one to
cancel any other functionality called cancelClick (the equivalent of
return false).

So, to overwrite a link like

<a href="help.html" id="help">Help</a>

you can do:

help={
	init:function(){
		if(!document.getElementById || !document.createTextNode){return;}
		var helplink=document.getElementById('help');
		if(!helplink) {return;}
		help.addEvent(helplink,'click',help.helpmagic,false);
	},
	helpmagic:function(e){
		var l=help.getTarget(e);
		alert(l.href);
		help.cancelClick();
	},
/* helper methods */
	getTarget:function(e){
		var target = window.event ? window.event.srcElement : e ? e.target : null;
		if (!target){return false;}
		if (target.nodeName.toLowerCase() != 'a'){target = target.parentNode;}
		return target;
	},
	cancelClick:function(e){
		if (window.event){
			window.event.cancelBubble = true;
			window.event.returnValue = false;
			return;
		}
		if (e){
			e.stopPropagation();
			e.preventDefault();
		}
	},
	addEvent: function(elm, evType, fn, useCapture){
		if (elm.addEventListener)
		{
			elm.addEventListener(evType, fn, useCapture);
			return true;
		} else if (elm.attachEvent) {
			var r = elm.attachEvent('on' + evType, fn);
			return r;
		} else {
			elm['on' + evType] = fn;
		}
	}
}
help.addEvent(window, 'load', help.init, false);

Looks bloated but once you have those it is pretty easy.
Safari doesn't play nice, if you want hack for it you need to add:
	init:function(){
		if(!document.getElementById || !document.createTextNode){return;}
		var helplink=document.getElementById('help');
		if(!helplink) {return;}
		help.addEvent(helplink,'click',help.helpmagic,false);
                helplink.onclick=function(){return false;} // Safari fix
	},


HTH
Chris


--
Chris Heilmann
Blog: http://www.wait-till-i.com
Writing: http://icant.co.uk/
Binaries: http://www.onlinetools.org/



More information about the thelist mailing list