dean.edwards.name/weblog/2005/10/add-event2/

addEvent() – Follow Up

This is a follow-up to my addEvent solution. From the comments to that post it is clear that there were a couple of things missing. The first was the ability to return a value from the handleEvent function. The second was the ability to use W3C standard methods to cancel the event and stop event propagation (event bubbling).

Below are the amendments necessary:

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(window.event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};

One other issue, pointed out by PPK (via email). If a page contains an onload attribute on the document body it will overwrite any previously attached event handlers on the window object. A bit of a nuisance but not disastrous.

<body onload="doSomething()">

I’ve updated the downloadable version: /my/events.js

Update. It is well worth reading Tino Zijdel’s summary of this method.

Comments (73)

Leave a comment

One minor quibble: handleEvent() will return true even when all attached handlers return nothing, i.e. null.

  • Comment by: Niko
  • Posted:

Niko – that is what is supposed to happen. Event handlers must specifically return false to cancel an event.

  • Comment by: -dean
  • Posted:

Should that be:

if (this.$$handleEvent(event) === false) {

I.e., 3 =’s? At least I was under the impression that falsish values weren’t good enough to return in event handlers, you have to return exactly “false”. And that “foo==false” is completely equivalent to “!foo”.

Ian – you’re right. I assumd that returning zero (or other equivalent of false) would cancel the event. After testing it seems that is not the case.

  • Comment by: -dean
  • Posted:

A possible solution for the body/window onload issue:

/*@cc_on @*/
/*@if (@_win32)
	document.write("<script defer>if(document.body.getAttribute('onload')){addEvent(window,'load',window.onload);window.onload=handleEvent}<\/script>");
/*@end @*/

Although this is IE-only, if you implement addEventListener for those browsers that support it it will be mainly IE that will have the problem.

  • Comment by: Tino Zijdel
  • Posted:

What do you do if there are multiple events attached to an element that return different values. One may return false, others may return true. It looks like handleEvent() only returns the last value.

I don’t know if this is important but I do know that the onsubmit event is cancelled if false is returned.

I can’t seem to get the addEvent function to work in Safari 2.0.1 when the page is served as application/xhtml+xml. Seems to work in Firefox as XHTML and in Safari served as text/html. The var handlers = element.events[type]; seems to be the problem. Any ideas what might be going on? Any insight would be much appreciated.

  • Comment by: Justin
  • Posted:

Tanny – handleEvent() will return false if either one of all attached handlers returns false, otherwise it returns true – as initialized in the 1st line of handleEvent(). Think of handleEvent() && handlEvent() && …

  • Comment by: Niko
  • Posted:

Justin: do you have the same problem with my hybrid solution (that implements addEventListener when it is available)? http://therealcrisp.xs4all.nl/upload/addEvent_dean.html

  • Comment by: Tino Zijdel
  • Posted:

Tino, in a quick (by no means thorough) test, your script seems to work in Safari on an XHTML 1.1 page served as application/xhtml+xml. I’ll try to do some more testing in the next couple of days. Thanks.

  • Comment by: Justin
  • Posted:

One other issue, pointed out by PPK (via email). If a page contains an onload attribute on the document body it will overwrite any previously attached event handlers on the window object. A bit of a nuisance but not disastrous.

Is there a fix?

  • Comment by: Jo
  • Posted:

I checked Tino’s page, there is a code block with a fix for the body onload ? Right?

  • Comment by: Jo
  • Posted:

Jo: yes, that’s a fix that I have come up with for the body onload issue. I first tried something along the lines of what I posted in comment #5 but that didn’t work out in IE5. I know Dean will probably disapprove of the use of onreadystatechange, but sofar it seems to work well at least for IE/Win which is probably the only browser that needs it since I use addEventListener for those browsers that support it. I have not thoroughly tested it though, so consider it ‘experimental’ ;)

  • Comment by: Tino Zijdel
  • Posted:

“I have not thoroughly tested it though, so consider it experimental”

@Tino

This means that if I do not use the body onload handler I can leave it out, right?

  • Comment by: Jo
  • Posted:

Jo: that’s right

  • Comment by: Tino Zijdel
  • Posted:

Hi Dean, I have a question.

I ran into browser-compatibility problems when I tried to forward events between objects, like this:

addEvent(obj, "click", function(e){
  return otherObj.onclick(e);
});

IE freaks out when I pass arguments to the onclick function, and Firefox freaks out if I don’t.

To remedy this I wrote a small sibling to handleEvent that performs/forwards events in a cross-browser compatible way:

performEvent = function(element, type, event) {
  return (window.event) ? element["on"+type]() : element["on"+type](event);
};

So, Dean, I wonder if you can think of a cleaner/simpler way to handle this problem?

  • Comment by: Már
  • Posted:

Hi Dean,

I discovered that any extension to Object (e.g. Object.prototype.doSomething()) also gets fired by the handleEvent() function. I added an extra test in handleEvent() to make sure that only registered events get fired:

function handleEvent(event) {
  ...
  for (var i in handlers) {
    this.$$handleEvent = handlers[i];
      if (this.$$handleEvent.$$guid && this.$$handleEvent(event) === false) {
...
  • Comment by: Daniel Frechette
  • Posted:

Daniel – try to avoid extending Object.prototype:

http://erik.eae.net/archives/2005/06/06/22.13.54/

this is considered bad coding practice and can mess up lots of things in script.

  • Comment by: -dean
  • Posted:

Dean, you are absolutely right. I made the necessary changes to my code to no longer extend Object. I took a few hours, but the effort was worth it.

Regards, Daniel

  • Comment by: Daniel Frechette
  • Posted:

Dean, I used extensively the described methods in my project, I really appreciate your work and copied some idea from it but I believe you missed on events coming from other sources than the current window, so hope this small one line diff helps make addEvent() the definitive reference.

event=event||getEvent(window.event||(this.ownerDocument?this.ownerDocument.parentWindow.event:this.parentWindow.event))

I have several smaller windows (iframes) inside the main window, and from there I use something like top.addEvent(element,’click’,myFunc,false) to add events in the smaller windows without the need to reload the addEvent() javascript in each window (also it is already cached).

The problem with the script is that you are pointing to a hard-wired ‘window’ without taking in consideration child windows or iframes (my situation).

If you have a better idea on how to do it please correct my code.

I believe addEventListener and attachEvent take this in consideration, so Tino idea of detecting capabilities (not browsers) in the following order (W3C Moz Others IE) is a good idea.

I had a chance to try everything on a beta of IE7 and the solution also works for it, it seems there are not big changes in it after all…

Sincerely,

Diego

This is somehow shorter, hope it works everywhere. Have not tested in all browsers.

event=event||getEvent(window.event||(this.ownerDocument||this).parentWindow.event)

It looks for the ‘ownerDocument’ in the element, from there it steps up to the correct originating window and then the event itself. If ‘ownerDocument’ is ‘null’ we have a document instead of an element.

Diego

What do you do if there are multiple events attached to an element that return different values. One may return false, others may return true. It looks like handleEvent() only returns the last value.

Application – DOM-based on-demand javascript library In the beginning of this year I was playing with JavaScript and various frameworks like Prototype [1]…

Hi, Dean,

I’m working on a large corporate/customer relations website that we are redesigning. Good news is that we have the go-ahead to build it using more standard DOM, JS, and CSS. The bad news is that our corporate baseline includes Mac IE 5.x.

*waiting for peals of laughter to subside*

Assuming that this baseline cannot be changed (it literally took three years to argue for presenting the site as unstyled to 4.x browsers), I am having difficulties making this work. Everything seems to work, including attaching the event handler to the object through this.$$handleEvent = handlers[i];. When alerting this.$$handleEvent, the function’s text is returned. Calling this.$$handleEvent(event), however, seems to do absolutely nothing. No alert() methods in the function display javascript alerts, no return values are returned, and the effects of the function are not implemented. Alerting this.$$handleEvent(event) returns null.

Does this sound familiar? Is it a known issue? Is there a workaround?

Thanks in advance,

Michael

  • Comment by: Michael Landis
  • Posted:

Oops, sorry — specifically this is not working for change events on SELECT elements.

  • Comment by: Michael Landis
  • Posted:

Hi Dean, any idea how to use this for DOMContentLoaded?

  • Comment by: siftee
  • Posted:

I plugged this into my scripts at work (just dropped it over my old addEvent) and clients started getting ‘stack overflow at line 0′ errors in IE. None of us could recreate the effect in the office but swapping the scripts back cured the problem… So there’s a memory leak somewhere. The fact that it only manifested when I was using your script makes me thing it’s a problem with your script but then it might well be my fault! This is a rubbish bug report, eh?! Thought I’d let you know though…

@Mike: Worst. Bug report. Ever.

Stack overflows are not caused by memory leaks they are caused by infinite loops. I suspect that your code is at fault. Because you have provided no example there is not much I can do about it.

  • Comment by: -dean
  • Posted:

I read this article a while ago but never thought about using this until I started with my own incredibly complicated JS project. I have a new bug for you Dean.

When you use the code for(var i in handlers){} you are looping through the hastable in the order in which handlers were added, but this is backwards from addEvent (aka: addEventListener/attachEvent).

// this code
addEvent(obj,"click", showClick1);
addEvent(obj,"click", showClick2);
addEvent(obj,"click", showClick3);
// should fire in this order...
showClick3()
showClick2()
showClick1()

All you need to do is make the handlers an array instead of a hastable and loop through in reverse. (which is what I did, thanks for the code!)

  • Comment by: Alex Lein
  • Posted:

siftee,

I’ve added the DOMContentLoaded loaded event to Dean’s addEvent and have an explaination at DOMContentLoaded Event for Browsers. I use a combination of methods to make it work for a large number of browsers.

[...] is te vinden in loadingScreen.js. Als je je afvraagt waarom ik geen gebruikmaak van een addEvent-functie om het tonen van het laadscherm te [...]

Thanks Tanny!

  • Comment by: siftee
  • Posted:

The handleEvent function is painfully slow in IE. This code brings my CPU to 50% usage when moving the mouse around:

addEvent(document, 'mousemove', function(){})

a blank function. A function of any real length will max out the CPU easily even if the first line is “return false;”.

I narrowed the problem down to the this.$$handleEvent = handlers[i]; line. Assigning $$handleEvent is slow, relatively speaking. I “solved” this by assigning attaching each function seperately (and more importantly, only once) based on its guid. The loop in handleEvent becomes:

for(var i in handlers){
	if(!this['$$event'+i])
		this['$$event'+i] = handlers[i];
	if(this['$$event'+i](event) === false) returnValue = false;
}

Which solves the problem. Although I think it is fairly likely that this introduces extra memory leaks. But maxing out my CPU by simply moving my mouse around is unacceptable :-)

  • Comment by: Mark Kahn
  • Posted:

[...] r not. This can cause serious problems and unexpected results. So imho it’s better to use Dean Edwards’ script. It provides the flexibility of addEventListener, and of course it works [...]

[...] http://dean.edwards.name/weblog/2005/10/add-event2/ // written by Dean Edwards, 2005 // with input from Tino Zijdel // [...]

I’ve only just stumbled onto the wonderful topic of unobtrusive javascript after reading Jeremy Keith’s ALA article: http://www.alistapart.com/articles/behavioralseparation

I came here after reading a comment in response to the article which recommended Dean’s method.

[warning]Newbie question[/warning]
I’ve read through the original post and some other related posts and have paid particular attention to the examples given by people when things don’t work quite as expected . . . but still I can’t quite figure how to correctly use the addEvent(), removeEvent(), handleEvent() and fixEvent() functions.

Is there any documentation floating around anywhere that explains, just briefly, how things work? I’m not asking for a detailed tutorial (where’s the fun in being handed the answer on a plate?), but some quick examples and a list of what values certain parameters can take would be nice.

I reckon I’ve missed the thing that got the ball rolling and have a decent gap in my understanding of this topic!

  • Comment by: Jon Cram
  • Posted:

Dean, I proposed a tentative patch to your addEvent() code back in #20 to handle the Internet Explorer cross window event problem, now here is the patch I extracted from my code that could succesfully be used in your code:

 event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);

Many implementations does not take this in consideration, hope it will be usefull for your addEvent() too.

Here is a test case (IE only problem) and an explanation of this on Matthias Miller blog.

[...] Eventually all this led to a addEvent() recoding contest where a lot of people contributed and a winner was announced. After that, there were some voices raised about the winner and his solution, and JavaScript hero Dean Edwards (amongst many others) released his version of addEvent. [...]

Great code. I was comparing yours and the Yahoo event manager and there was one difference I noticed when I attached a click event to the document object.

In Yahoo’s this syntax a href=”http://someurl.com” onclick=”window.open(this.href,’popupwindow’,'width=800,height=550,’); return false;”

allows a pop-up window to open without navigating to a new page. But with this addEvent code, IE will navigate to the next page in addition to opening the pop-up window.

Now I know that we should be moving away from onclicks in anchor tags, but I have some legacy code that I wanted to lay the new event managers over. Any ideas what is causing IE to navigate to a new page?

  • Comment by: Dennis
  • Posted:

Sorry if I am rude. But dean’s version VS Tino Zijdel’s version.

What are the main differences? I cant decide to use which one, because both does the job here and I am not good enough to spot the advantages/disavantages.

And I think more people would like to know also :P

  • Comment by: Alow
  • Posted:

@mike & @dean: I am also experiencing stack overflow at clients computers and traced it to users that has Norton Internet Security installed (supposedly also with other Norton products). It is the popup blocker that inserts the following snippets of code: http://www.aestheticbliss.com/nis.txt

This somehow interferes with addEvent and causes a stack overflow in IE. I am trying to solve this problem as there are a fair few of our clients that has NIS installed. Any insight is much appreciated!

  • Comment by: Rune Sandberg
  • Posted:

A previous poster requested some simple examples of where to place the addEvent and removeEvent calls. No one has responded yet so I woudl like to make this request again. Placing the addEvent in the head of the document seems logical but where is the best place to put the removeEvent call?

  • Comment by: David Baldon
  • Posted:

@David – You usually don’t need to call removeEvent. It is there only for temporary event handlers.

  • Comment by: -dean
  • Posted:

Hi

I’ve trying to use your addEvent function to tidy-up a project I’m working on. It consists of a large number of forms, each with a validation function, currently called from the onsubmit attribute on the form tag.

onsubmit=”return check()”;

The check function is in a js file and I’d like to inject the check() function from within the js file too. I’m trying the following code, but this only works in IE, not Firefox or Opera. In those two browser, the check() function is called but the form is submitted regardless of the return value.

function check() { //return true or false }

function injectSubmit() { var lForm; try { lForm = $(‘loginForm’); } catch (ex) {} if (lForm) { addEvent(lForm, ‘submit’, check); } }

addEvent(window, ‘load’, injectSubmit);

Notice that I’m using the Prototype library function $() to get the form object. Any ideas where I’m going wrong?

Thanks

Michael

I get a stack overflow when I have the skype 2.6 (beta) toolbar installed.

  • Comment by: Harry
  • Posted:

[...] addEvent() method http://dean.edwards.name/weblog/2005/10/add-event2/ [...]

I got a small problem concerning the length of arguments passed to a function.

I have build a function which should be fired onclick of an element. The function checks for the number of arguments. But I always get 1 as a result of arguments.length when I add the event like this:

addEvent(object,’click’,doAction);

I noticed that the length of arguments is correct when I add it like this:

addEvent(object,’click’,function(){ doAction(); });

But this is just dirty don’t you think? :)

  • Comment by: Patrick
  • Posted:

[...] Dean Edwards’ fantastic work with checking for DOM loading and proper adding of events. [...]

[...] addEvent() Follow Up – Dean Edwards Inga mer inline eventhandlers nu. (tags: javascript addevent tutorial) [...]

Hi Dean, I believe this small patch will correct the returned value in cases where it needs to be something different from a TRUE/FALSE boolean. This is not a problem normally but in some situations this is required to emulate standard (!^!) browser behavior.

This is needed for example by the “onbeforeunload” event to be able to overcome the alert dialog warning when leaving the page (need to return undefined) or to just send back a string that will appear in the dialog box itself (a string in this case). I tested this behavior to be consistent on Firefox, IE and Opera.

From what I understand event handlers may return any type of value including “undefined” or void(0), and this is normally the default when there are no return values. This is the reason the “returnValue” is declared but not assigned any value.

Another thing to notice is that if an handler in the chain return false, the loop must exit and the remaining handlers for that chain are not executed. I believe this is the correct implementation however I would like to hear your comments on this.

function handleEvent(event) {
    var returnValue;
    // grab the event object (IE uses a global event object)^
    event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
    // get a reference to the hash table of event handlers
    var handlers = this.events[event.type];
    // execute each event handler
    for (var i in handlers) {
        this.$$handleEvent = handlers[i];
        returnValue = this.$$handleEvent(event);
        if (returnValue === false) {
            break;
        }
    }
    return returnValue;
};

Having read through all the previous comments I believe it is possible that some of the problems mentioned above can have a solution (like #39 for example) and the “break;” statement to exit the loop is an answer to the question raised in #22, the first handler returning false will cancel the remaining handlers for that type of event.

Have a good time,

Diego

Nice work, Diego!

  • Comment by: -dean
  • Posted:

[...] 当然最好还是推荐使用 addEvent 函式…… 如果 不想有的时候 IE 被杀掉的话…… 载 addEvent.js 之后…… 如此这般一下: [...]

[...] 当然最好还是推荐使用 addEvent 函式…… 如果 不想有的时候 IE 被杀掉的话…… 载 addEvent.js 之后…… 如此这般一下: addEvent(window, ‘load’, resizeImgs); [...]

[...] 但是,如果我们通过JavaScript来添 事件处理函数,this引用的是生成该事件的DOM元 。(注意:此处的事件处理非常简洁和易于阅读,但其他的就别有洞天了。请使用真正的addEvent函数取而代之): [...]

Anyone else notice that even if you remove all handlers from an element, it’s still firing the handleEvent handler? Add a console.log message before the loop in handleEvent and you’ll see.

  • Comment by: tuan
  • Posted:

[...] the addEvent by Dean Edwards [...]

function fixEvent(event) {
// add W3C standard event methods
event.preventDefault = event.returnValue = false;
event.stopPropagation = event.cancelBubble = true;
event.target = event.srcElement;
return event;
};
is this ok to do so ?

  • Comment by: shirirules
  • Posted:

[...] 但是,如果我们通过JavaScript来添 事件处理函数,this引用的是生成该事件的DOM元 。(注意:此处的事件处理非常简洁和易于阅读,但其他的就别有洞天了。请使用真正的addEvent函数取而代之): [...]

event = event || fixEvent(window.event); this will always be null in case of addEvent(window,”onresize”,myOnResizeFn) on FF/Opera. Also the scope is passed to window and if myOnResizeFn is not prototyped to window it will also throw an error. I sugest iffing it out or something.. what do you guys think?

  • Comment by: Kriminel
  • Posted:

Anyone know why this code would conflict with Omniture’s SiteCatalyst javascript files?

this.events has no properties: var handlers = this.events[event.type];

  • Comment by: Marc
  • Posted:

[...] As well as Dean Edward’s addEvent2 script: http://dean.edwards.name/weblog/2005/10/add-event2/#comment196705 [...]

Marc, the Omniture code is changing the reference to your “this” keyword. Read more about it in my post: http://readystate4.com/2008/03/11/issue-with-omnitures-site-catalyst-form-analysis-plug-in/

  • Comment by: Mauvis
  • Posted:

[...] Dean Edwards – addEvent() – My Solution que luego publicò este otro post addEvent() – Follow Up [...]

[...] overwrite any other onload actions you may have defined. If you get the addEvent() function from: http://dean.edwards.name/weblog/2005/10/add-event2/ …. you could change this into: addEvent(window, "load", function(){ MyClass.init(); [...]

  for (var i in handlers) {
    this.$$handleEvent = handlers[i];
    if (this.$$handleEvent(event) === false) {
      returnValue = false;
    }
  }

In case Object.prototype is polluted (adding a new method by default, or others), the above codes may throw exceptions. What about adding validations like:

for (var i in handlers) {
	if (isNaN (i)) {
		continue;
	}
	this.$$handleEvent = handlers[i];
	if (typeof this.$$handleEvent != "function") {
		continue;
	}
	if (this.$$handleEvent(event) === false) {
		returnValue = false;
	}
}

HEY GUYS, THANKS FOR ALL THE EFFORT. DEAN IN PARTICULAR. I WAS DIRECTED TO YOUR ADDEVENT SCRIPT FROM Stephen Chapman’S SITE PROMOTING UNOBTRUSIVE JAVASCRIPT WHICH CONVINCED ME TO TAKE ALL OF THE INLINE SCRIPT OUT AND PUT THE JS.FILE LINK JUST BEFORE THE CLOSING BODY TAGS. THE SITE I’M WORKING ON IN IE8 IS IN IT’S OWN FOLDER ON MY PC. AND I’M NOT GOING TO LOAD IT TO THE DOMAIN UNTILL I’M SURE IT WORKS. THE INDEX PAGE IS SET TO NO SCROLL AND CONTAINS A LOGO HEADER ACROSS THE TOP AND PRODUCT LINKS ON THE RIGHT. THE LINKS CALL PRODUCT PAGES THAT LOAD IN AN IFRAME IN THE CENTER ID “DISPLAY” EACH PRODUCT PAGE HAS IT’S OWN JS.FILE LINK/SCRIPT TAGS SET JUST LIKE THE INDEX PAGE BEFORE THE CLOSING BODY TAG. ALL HAVE THEIR OWN CSS FILES LINKED IN THE HEAD TAGS. WHEN THE INDEX PAGE LOADS IT’S JS.FILE WRITES A DOCUMENT TO ANOTHER IFRAME ACCROSS THE BOTTOM ID “REGISTER”.THE DOCUMENT IS TITLED “CHECKOUT” WHEN A PRODUCT PAGE LOADS IN “DISPLAY” THE GREETING DIV IN “REGISTER” IS HIDDEN TO REVEAL A FIXED TABLE HEADER AND ONE ROW OF THE TABLE WITH, CODE,ITEM,COLOR,SIZE,QUANTITY,PRICE,TOTAL AND CLEAR. WHEN A CLIENT CHOOSES A PRODUCT FROM ANY OF THE PRODUCT PAGES LOADED IN “DISPLAY” BY CLICKING A BUYNOW BUTTON IT CALLS A FUNCTION THAT INSERTS THE FIELDSETS INPUT VALUES INTO ROW INDEX 1 OF THE CHECKOUT TABLE IN “REGISTER”. WHEN THE CLIENT WANTS TO CHECK OUT HE PRESSES A BUTTON ON THE INDEX PAGE AT THE BOTTOM LEFT UNDER THE PRODUCT PAGE LINKS THAT LOADS THE UNCLOSED “CHECKOUT” DOCUMENT TO “DISPLAY”. THERE THE CLIENT CAN CLEAR ANY ITEMS THEY DO NOT WANT BEFORE SUBMITING THEIR ORDER. WITH THE SCRIPTS WRITEN INLINE I ACTUALLY HAD THIS FUNCTIONALITY. I KNOW THAT Stephen Chapman’S SCRIPT IS MODIFIDE AND OMITS SOMETHING LIKE “fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);” BECAUSE THOUGH THE CASH REGISTER SOUND PLAYS WHEN THE “CHECKOUT” BUTTON IS PRESSED. THE CHECKOUT DOCUMENT NO LONGER LOADS TO “DISPLAY”. THIS IS THE ADDEVENT SCRIPT THAT I USED CURTESY OF DEAN AND CHRIS. I’LL CHECK TO SEE IF ADDING DIEGOS SNIPIT CORRECTS THE ISSUE BUT COULD USE AN EXPERTS LOOK AT THE FUNCTION SYNTAX. SOMEBODY ALREADY SUGGESTED THAT THE # IN ‘checkout.html#login’ WOULD CAUSE PROBLEMS WITH IE BUT EVEN WITHOUT IT THE PAGE DOESN’T LOAD. I REALIZE THAT THE WRITE STREEM ISN’T CLOSED AND THE DOCUMENT NAME RETURNS UNDEFINED BUT AS I SAID BEFORE, WHEN THE SCRIPT WAS WRITTEN INLINE IT FUNCTIONED. THIS IS THE UNOBTRUSIVE INDEX SCRIPT. IT WOULD BE GREAT IF JAVASCRIPT COULD WRITE THE ‘NAME’ OF THE DOCUMENT BUT I’M GUESSING THAT’S A READ ONLY PROPERTY OF THE DOCUMENT OBJECT IN JAVASCRIPT? ANY THOUGHTS ON THE FUNCTION SYNTAX WOULD BE APPRECIATED. THANKS AGAIN FOR THE ‘ADDEVENT’ SCRIPT. WE ARE ALL ONE STEP CLOSSER TO THE ‘UNOBTRUSIVE’. MAYBE THEN I COULD GET SOMEBODY ELSE TO WRITE THE SCRIPTS.

function EvalSound(soundobj) {var thissound=document.getElementById(‘sound1′); thissound.Play();}

function loadorder(){top.frames['display'].location.href=’checkout.html#login’;}

function addEvent(el, eType, fn, uC) { if (el.addEventListener) { el.addEventListener(eType, fn, uC); return true; } else if (el.attachEvent) { return el.attachEvent(‘on’ + eType, fn); } }

addEvent( document.getElementById(‘placeorder’),’click’,loadorder,false);

addEvent( document.getElementById(‘placeorder’),’click’,EvalSound,false);

  • Comment by: Heinz Stapff
  • Posted:

[...] 在ppk的竞赛结束之后,作为评委的Dean Edwards也写了一个自己的addEvent()函数: [...]

Hi, how can I clone events to another DOM element ?

  • Comment by: Fabien
  • Posted:

[...] 二、Dean Edward 所写的 addEvent() 函数 :http://dean.edwards.name/weblog/2005/10/add-event2/ [...]

[...] Dean Edward 所写的 addEvent() 函数 :http://dean.edwards.name/weblog/2005/10/add-event2/ [...]

[...] 这个方案比较特别。详细请移步这里 [...]

[...] [...]

[...] 二、Dean Edward 所写的 addEvent() 函数 :http://dean.edwards.name/weblog/2005/10/add-event2/ [...]

Leave A Comment

Line and paragraph breaks automatic, email address never displayed. Some HTML allowed.