with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

Forget addEvent, use Yahoo!’s Event Utility

Wednesday, March 1st, 2006

After spending a few hours getting comfortable with Yahoo!’s new Event utility that was recently released along with many other sweet tools via YUIBlog, I became convinced that it is the dopest, sweetest, most tight, most sexiest event utility on the planet. With a little crunching and some gZipping I was able to get this puppy down to meezily weezily 2k.

Furthermore, when I say forget addEvent, I mean any and every version of addEvent you can think of. This goes for Scott Andrew’s original addEvent function, every entry from the addEvent recoding contest, even Prototype’s Event observer and its many properties and extensions. I even had a stab at it myself and was pretty impressed with the outcome.

With all that said, not only is the Yahoo! event utility fresh and so clean by cleaning up some of the mess that other addEvent functions leave behind, it does indeed do quite a few other clever things you wouldn’t expect but will knock your socks off. To get started in experiencing this sweet dope tight sexy Event utility, simply plug in the following files into your JavaScript document as follows:

Inserting the YUI Event util

<script type='text/javascript' src='/path/to/YAHOO.js'></script>
<script type='text/javascript' src='/path/to/event.js'></script>

In my particular case after crunching and gZipping it, the filename changed to event.php and I inserted the following lines of code at the very top:

gZipping it up

<?php
ob_start ('ob_gzhandler');
header('Content-type: text/javascript; charset: UTF-8');
header('Cache-Control: must-revalidate');
$offset = 60 * 60 * 24 * 30;
$ExpStr = "Expires: " .
gmdate('D, d M Y H:i:s',
time() + $offset) . ' GMT';
header($ExpStr);
?>
/* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
/* The rest of the code goes here...*/

Awesome, now that that’s out of the way, lemme tell you just a few of it’s slick features…

It’s Dope because…

It’s got Handler Attachment Deferral. According to the event utility API document: If you attempt to attach a handler to an element before the page is fully loaded, the Event component will attempt to locate the element. If the element is not available, Event periodically checks for the element until the window.onload event is triggered. Oh my F’Gosh! Is that not dope? In a way, it cleans up your mess just incase you goofed.

It’s Sweet because…

It’s got Automatic Scope Correction. By default in Internet Explorer (using the attachEvent method) when you look at the this object within your callback function, it looks at the window object whereas according to DOM2 methods it should be the element from which triggered the event. The YUI Event.addListener method corrects this behavior and appropriately changes the scope for you. Albeit some of the entries from the recoding contest fixed this as well, this is indeed another reason why this thing is also so sweet. Also note that Prototype.js does not do this by default but Ryan Campbell has shared with us a workaround to maintain it. Eitherway, no workarounds here, it just straight up works out of the box.

An example of this behavior would be like the following piece:

this correction

YAHOO.util.Event.addListener('myObj','click',callback);
function callback() {
	alert(this.id);
	// 'this' is a reference to myObj
}

It’s Tight because…

It’s got Automatic Event Object Browser Abstraction. What this means is that we no longer need to look at window.event when sniffing for the event type. This is automatically passed in as the first parameter into the callback function. For example:

Example of event abstraction

function callback(e) {
	// that's right. 'e' is what you think it is
	// Even for Internet Explorer!
}

Not only is that tight, but they’ve got built in features that allow you to do all those useful things you normally do with ‘e’ anyway. For instance, if you want to pull a preventDefault to stop the default action from firing, you can simply do the following (including others):

Preventing default actions

YAHOO.util.Event.addListener(myObj,'click',callback);
function callback(e) {
	// not so fast there cowboy
	YAHOO.util.Event.preventDefault(e);

	// Oh, you don't want bubbly wubbly? Fine.
	YAHOO.util.Event.stopPropagation(e);
}

Oh, tired of doing the same two lines of code everytime you want to stop events like that. Well why not just use the handy-dandy stopEvent method.

stopEvent to the rescue

function callback(e) {
	// Pa-Zow Sucka!
	YAHOO.util.Event.stopEvent(e);
}

Oh yea, you know you like it. But we haven’t even scratched the surface yet. Behold its sexy features…

It’s Sexy because…

You can send an arbitrary Object to the Event Handler.

Say What?

Yea, try this on for size. You can pass in an object as a fourth parameter to the addListener method which becomes available to you as the second parameter in the callback function. For example:

Arbitrary Object passing

YAHOO.util.Event.addListener('myelementid', 'click', callback, myOtherObj);
function callback(e,el) {
	// el is a reference to myOtherObj
	el.className = 'hoopla';
}

Tell me that’s not sexy. Go ahead. Try me. Oh, I get it, you want more. Well then, if that doesn’t tickle your soft spot, there’s yet another optional parameter you can pass into the addListener method which is a boolean (when set to true) that will adjust the scope of this to be set to the custom (arbitrary) object that you passed in. For example:

arbitrary object is accessed through “this”

YAHOO.util.Event.addListener('myelementid', 'click', callback, myOtherObj,true);
function callback() {
	// myOtherObj is 'this'
	this.className = 'hoopla';
}

Not convinced yet? Let’s get naughty

Believe you-me. What I’m about to show is going to make you cry (even my wife is jealous). It’s time to have fun with arrays. With the Yahoo! Event utility you can do things that no other addEvent wannabe has even come close to, and that’s being able to assign events to multiple objects at the same time with just one line of code. Check this out:

Assigning events to an array of objects

var cloner = {
	init : function() {
		YAHOO.util.Event.addListener(['box1','box2','box3','box4'],'click',this.swap);
	},
	swap : function() {
		$('someDiv').innerHTML = $(this).innerHTML;
	}
}

Yea, you saw what just happened. I passed in ['box1','box2','box3','box4'] as the element reference to run the swap method upon the ‘click’ event. This means that when I click on any of those four boxes, I will get my callback function. Not only does it have to be a string reference of the id’s, but it can be mixed strings and objects. For example:

Example of strings and objects mixed

var cloner = {
	init : function() {
		var obj1 = document.getElementById('box7');
		// or if you prefer the $dollar function
		var obj2 = $('box39');
		// then pass them into the array
		YAHOO.util.Event.addListener(['box1',obj1,'box3','box4',obj2],'click',this.swap);
	},
	swap : function() {
		$('someDiv').innerHTML = $(this).innerHTML;
	}
}

Alright, so I know what you’re thinking. Does that mean I can use Dustin’s getElementsByClass function and pass in the array which will, in return, assign listeners to the object collection? Indeed my dear beloved friends. Indeed.

Let’s pretend we have a bunch of <div> elements around the page with the class name of ‘box’ and we want to attach the same function to all of them. Check this out:

assigning events via getElementsByClass

var boxes = getElementsByClass('box',document,'div');
YAHOO.util.Event.addListener(boxes,'click',this.toggle.changer);

Uh huh, it really is that easy. Didn’t think it could get better? Oh boy, lest we forget, we can do this with our arbitrary objects as well. See below:

Multiple Arbitrary Objects getting love

var others = ['green','blue'];
YAHOO.util.Event.addListener('red','click',this.toggle.changer,others);

In this case of toggling the display of an element, we can indeed click on one element to toggle many ‘other’ elements at the same time. Or click on many elements to toggle one element. Or for that matter, we can click on many elements to toggle many other elements…

many to many fiesta

var repubs = ['orange','red'];
var democs = ['blue','green'];
YAHOO.util.Event.addListener(democs,'click',this.messWith,repubs);

I’m in love, anything else I should know about this?

Sure, there’s quite a few other useful snippets built into this badboy such as Event.getPageX and Event.getPageY that will return mouse coordinates in a cross-browser friendly way as well as Event.getTime and Event.getCharCode that can prove to be useful as well. I also mentioned a few above already with the stopEvent methods which makes for a helluva convenience.

All in all I have found a new love for event attachment and Yahoo! has exceeded well beyond my expections. As of now this website is currently using my old addEvent but expect that to change in the near future as I will be adopting this utility from here on out.

See this stuff in action

Just for kicks, I put together a little demo of most of these examples into practice for those who want to get a closer look at the code. See Event Listening gone Mad! and feel free to peak at the code and adopt these practices yourself.

121 Responses to “Forget addEvent, use Yahoo!’s Event Utility”

  1. Elliot Swan

    Dang, that is pure sweetness.

    Funny thing is, about ten minutes ago I was just here to get your addEvent(), then I came back to look at your JSON article and saw this.

    I think I’m going to have to redo my script now.

  2. Elliot Swan » Forget addEvent

    Trackback: Forget addEvent, use Yahoo!’s Event Utility–Dang this is awesome…

  3. Nate Cavanaugh

    Holy crap, the only thing sexier than this is my wife.

    Here goes to installing another mini-library :D

    And rock freakin on for the BSD license :)

  4. Kelly Miyashiro

    Even though I don’t know any javascript, that’s very impressive.

    I have a question though, since you’re toggling the style of the boxes in the example page to “display: none”, why doesn’t the black box move up and to the left when the other boxes disappear? I guess because the browser doesn’t render the page etc and that’s what makes “AJAX” so special? I’m not sure how pure javascript works. This makes me want to learn it though.

  5. Dustin Diaz

    Kelly, the toggling that’s going on isn’t moving the others mainly because they’re all absolutely positioned with CSS. Had they been floated or simply just stacked on top of each other they would indeed shift and move around.

    Bare in mind that none of this has anything to do with Ajax, the toggling in the demo of this article is simply just manipulating the ‘display’ of each element.

    If you’re looking to get into Ajax without having to learn much, you can indeed use Yahoo’s connection manager as I’ll proudly stand by that one. It too is sexy in its own ways as well.

  6. Douglas Clifton

    Whenever I mention gzip compressing CSS or JavaScript, in particular with a PHP, I’ve always gotten a hailstorm of folks crying “IE can’t handle it, or IE won’t cache it!” I take it you’ve tested your wrapper to make sure all is well?

  7. P.J. Onori

    I’m still waiting for custom event creation. I long ago fell in love with this in Actionscript and I just assume that other languages have it.

    Don’t get me wrong, this is absolutely great. Very awesome stuff. Nonetheless, call me greedy - I want custom event creation. :)

  8. Binny

    function addEvent(element,event,callback) {
    YAHOO.util.Event.addListener(element,event,callback);
    }
    And I don’t have to re-write all my script. Is there any problems with this approch?

    Of course, for Multiple Arbitrary Objects support you will still have to call it the old way - but for most of my needs, addEvent() will be enough.

    Thanks for the info.

  9. bookwyrm

    P.J. - you do have custom event creation.

    I just played with it a bit and it works like a charm.

    Dustin, great article. Thanks a bunch.

  10. Jeriko One » Blog Archive » addEvent vs. Yahoo’s Event Utility

    […] Dustin Diaz hat sich mit den kürzlich erschienenen Event Utility von Yahoo beschäftigt, zu finden hier. Und anscheinend hat ihn die Funktionalität ziemlich überzeugt. Tell me that’s not sexy. Go ahead. Try me. Oh, I get it, you want more. Well then, if that doesn’t tickle your soft spot… Dustin Diaz […]

  11. rovas

    Hi all, a little bit Off-topic… If someone is interested in php gzipping while reading this interesting post as me, I found this (http://www.ilovejackdaniels.com/php/php-gzip-and-htaccess) explanation which may be in help.

    thanks for the impressive article Dustin

  12. Jim A.

    [bquote]
    // Pa-Zow Sucka!
    [/bquote]
    Classic!

    Anyway, this is absolutely fantastic. Dustin, thanks for the needed kick in the pants to start digging in and using the YUI. I am in love.

  13. Dustin Diaz

    @bookwyrm: Thanks for clarifying to P.J. - there is indeed custom event creation :) That’s what makes it so… tight? lol.

    @Binny: That will work I ’spose. Nothing wrong with creating your own custom functions to call Yahoo’s utils :)

    @Douglas: As far as I know, IE won’t exactly be caching it as is, but I did set a “future expires header” on it hoping that would prompt IE not to check again for a while. Then again, worse case scenario, you’d have to redownload the 2k - not too bad at all.

    @rovas: Yea, that was a good article on it. Also Mike P wrote one about gZipping your CSS a while back.

    @Jim: Are you in love too? hehe. Pa-zow!

  14. Chris Pederick

    Awesome write-up, Dustin. The one thing missing from these Yahoo! libraries has been an easy to follow explanation of how to use them.

    Now you just need to do the same thing for the other libraries like the connection manager and the DOM! :)

  15. Leevi Graham

    Maybe I am misunderstanding the reference to ‘this.swap’in the code example: ‘Assigning events to an array of objects’.

    I thought that the ‘this’ keyword related to the element that fired the event not the object that assigned it in this case ‘var cloner’.

    Can someone clarfiy how to add an event and reference the object that the attach event code is located in?

  16. Dustin Diaz

    @Chris: It is indeed on my schedule to write about the rest. After corp (Yahoo!) looked at this you might see some of my articles landing on the YUIBlog website.

    Other than that, thanks for the encouragement. All in all, you should be thanking the developers who wrote them. I was personally thanked by the author of the YUI Event utility so that was sweet :)

    @Leevi, this.swap is the callback function I called. since it was wrapped in an object literal, it was a direct method of that object I was calling. You are indeed correct in saying that the ‘this’ keyword is related to the element that fired the event.

  17. Justin Palmer

    Nice article Dustin. The Yahoo Event model has definitely one-upped the Prototype Event model, but we are beefing up Prototype by adding some of these. Event polling which just rocks).

  18. Leevi Graham

    Is this a feature of the Yahoo Event or does your rock solid event handler provide similar ‘this.yourObjectMethod()’ functionality? I have tried this before with Rock Solid and I was returned an undefined..

  19. Joel Birch

    Hi Dustin - you have forced me out of “lurk mode” with this!

    Just had a quick go at using this, not just because of the droolable features, but mainly because I was getting javascript errors using Rock Solid in IE5 (Object doesn’t support this property or method - think its something in the eventCache function but as you probably can tell I’ve got LOTS to learn) and was hoping this method would not. No such luck. I am thinking maybe this is a “to hell with bad browsers” thing - is this the case?

    Also, I can’t get Safari to cancelDefault with this so I added back in a cancelClickSafari method (old school) but this still doesn’t work. Any ideas? If its obvious that I have no clue and am missing really obvious things, feel free to ignore me - you have far better things to do (Love SweetTitles - thanks heaps!). Cheers

  20. Douglas Clifton

    @Joel

    See Nate Koechley’s Graded Browser Support at the Yahoo! Developer Network for details on their approach to this issue.

  21. Henri Sivonen

    It still does “isIE: (!this.isSafari && navigator.userAgent.match(/msie/gi))”, though. :-/

  22. Edward Eliot

    Great write up - thanks for this Dustin. It has helped to clear up a few aspects I was unsure about and also expose a few extra cool features I didn’t know about.

    I wondered if the library ought to expose a universal version of the mouse “button” property for detecting which mouse button had changed state. I have an idea that Netscape 6 gets the values wrong 1,2,3 instead of 0,1,2 and wondered if any other browsers do too.

  23. Joel Birch

    Thanks Douglas.

    I had read that before but thanks for the nudge back on course.

    I notice that it works in IE5.5 which is A-grade and gives errors in IE5 which is C-grade - which is fine and I am happy to live with that. However, I was expecting more “unobtrusive” behaviour in IE5 at least, such as degrading gracefully (default behaviour re-instated) and no errors. I suppose this would be something I would have to write more conditional code for maybe?

    I noticed Safari (1.3 and 2) is A-grade, and for some reason (probably because its not 3am anymore (Australia)) I have it working in that browser now which is great.

    Thanks again!

  24. Joel Birch

    About my last comment: having just fixed a CSS issue which was making my links move when pressed in IE5, I notice that the default behavior *is* reinstated which is great. It still displays the dreaded error icon though.

  25. Michael Newton

    Nice stuff! I downloaded the connection manager to give it a try last week, so this entry was very timely for me. Playing with the events, I’m having even more fun!

    I’m glad you linked to your getElementsByClassName function as well; I’m finding it very useful. One thing nobody seemed to mention in the comments for that item is that you can pass it a regular expression, not just a class name! Very handy.

  26. Andrew Tetlaw

    You know Dojo has had this for ages too:
    http://dojotoolkit.org/docs/dojo_event_system.html

  27. Roman Rahman

    Surely it’s not a surprise. I think about another problem I described in my blog http://cute-solutions.blogspot.com/2006/02/order-of-events.html

    What’s about the order of more than one event listeners for single element?

  28. minghong

    What about assigning events to objects that have no ID set? e.g. those created by document.createElement.

  29. Olle Jonsson’s Morningstar » Javascript ate my hamster: Go get Yahoo Event Utility and Firebug

    […] Dustin Diaz tells about Yahoo Event Utility which is the addEvent killer of all time. If you do serious Javascripting these days, please, do yourself a favour, and read that piece. Slowly. You might find drool on your chin afterwards. Then, go get the Event Utility. You owe to yourself. You deserve it.And, be sure to get Firebug, while you are at it. It is Firefox-only debugging nirvana. Just exhale, and see the internals of your web apps. (And others’ web apps, as well.)The times they are a’changing. I love today’s stuff. Be safe out there. Me: back to the cave. […]

  30. Blair Mitchelmore

    Awesome site, and awesome article, it converted me to yahoo’s event system, but there’s just one parenthetical problem that hit me in this article…

    Shouldn’t “…there’s yet another optional parameter you can pass into the addListener method which is a boolean (when set to true) that will adjust the scope of this…” be “…there’s yet another optional parameter you can pass into the addListener method which is a boolean that (when set to true) will adjust the scope of this…”

    Unless of course the fifth parameter can be something (usable) other than a boolean.

  31. Phil

    Thank you for this. I’ve been trying to figure out “Event”. I’m not a JavaScript expert, and the YUL documentation is nice, but not as obvious as I would like. Examples and explainations are a good thing! {grateful vibe} :-)

  32. Dojo taking on YUI Event util

    […] Today I found a disturbing post from Derek Lakin encouraging developers to Forget Yahoo!’s Event utility, use Dojos event system. Obviously this was a direct hit on my recent entry on Forget addEvent, use Yahoo!’s Event utility covering just a few things that made it so cool. […]

  33. Shawn Wilsher

    I’ve been playing with this, and I have to say that this is an awesome tool. Thank you for pointing this out!

  34. planet::dojo » Still using a DOM-only event system?

    […] It’s often said that dojo.event.connect() is crack for web developers. Now that other folks are starting to notice that you can do better than DOM 2 event handling, there’s a chance for the webdev community to pull itself up even further from the primordial DOM event mess and deal with components and higher-order functions with a unified interface. dojo.event.connect() can help. […]

  35. S. Denman

    getElementsByClass is great, but it isn’t deferred, so I’m thinking of modifying the event system to accept id strings with some kind of code to indicate that it’s a class.

    for example:

    YAHOO.util.Event.addListener(’@myClass’, ‘click’, callback);

    which would be equivalent to:

    var elems = getElementsByClass(’myClass’, null, ‘myTag’);
    YAHOO.util.Event.addListener(elems, ‘click’, callback);

    …except deferred, of course!

    The only issue I can think of is that class strings must always be added to the deferred listeners list (unless the page has loaded) because you don’t know when all elements of that class type have loaded, so you need to keep scanning for them until the page finishes loading.

  36. Ara Pehlivanian

    Darn good post man. Excellent breakdown.

  37. Cultivate, Battle, Learn » Blog Archive » Outbound Link Warnings with YUL

    […] In addition to the site mentioned above, Forget addEvent, use Yahoo!’s Event Utility was a big help too. […]

  38. Jake

    Oh great - just what we need - another meaning for the word “dope”. Can’t quite figure out the spin you’re putting on it, though. What’s up with that?

  39. Harvey Ramer

    This looks like a time-saver. Alot of powerful features in one package. I no longer need to cobble event management puzzle together. Here it is!

  40. peterp

    Now, I just want to point out before I post that I know YUI has a drag-drop library but all I want is just “drag.” I simply want to drag a div around…

    I used the drag-drop library and it worked fine, it was just really slow and “chugged.”

    Was thinking that creating my own using the YUI events would be faster, any thoughts?

  41. Dustin Diaz

    Peter. The drag and drop util when I used it seemed to work pretty well (and very simple). So with that in mind, I’d still recommend the YUI drag’n drop - especially since it works in all the cross-browser work arounds for you.

  42. peterp

    Thanks Dustin.

  43. Erde

    Very good article! Thanks!

  44. neuemusic.com » Blog Archive » Toggler

    […] Last week however, I saw this article over on Dustin Diaz’s site and thought it might be worth checking out the Yahoo! UI Library (a.k.a. YUI). Although I do like the Scriptaculous library it feels quirky to me and still feels heavier than need be for what it offers. I am currently working on a project at my day job where I am integrating DWR for server to client communication (which is pretty slick feeling!) and utilizing the YUI lib for effects and events. I love the feel of the event implementation in YUI, and they do have a bit of documentation, which can be rare in this area of the world. […]

  45. JavaScript Scope Adjustment

    […] Now anytime we click on any of our boxes, they instantly become black. But we’ve already had enough on the Event utility, and besides, you can learn all about its uses on why this thing kicks mucho bottom, the point of this article is to learn scope adjustment. […]

  46. MiSHAK

    Great - on[event] - addEvent - Yahoo!
    IMHO does anyone read Gmail JavaScript source?
    What will bring us Google? LOL

    BTW: I was just dreaming why are the inputs (in reply form) so big ;)

  47. Episode 12: YUI Library Discussion

    […] We also got into detail as to what a Custom Event is - hopefully giving Adam Moore the justice he deserves for writing this into the Event Utility. […]

  48. Richard@Home » Blog Archive » links for 2006-05-24

    […] Forget addEvent, use Yahoo!’s Event Utility Dustin extolls the virtues of the Yahoo! Event Utility library. AddEvent just got even easier (tags: javascript dom event api library addevent) […]

  49. Diego Perini

    Dustin, related to the ‘this’ keyword you say:

    >according to DOM2 methods it should be the element from which triggered the event

    that was confusing to me…also I could be wrong in understanding since English is not my primary language.

    According to W3C DOM2 the ‘this’ keyword should be a reference to the object to which the event handler was attached to.

    This is not ALWAYS a reference to the element that fired the event, but sometimes it can be that way…

    As a test I tried to replace the event system in my project with YAHOO.util.Event and it WORKED…

    Great job of Yahoo, however there are still MEMORY LEAKS in this part of Yahoo’s event.js:

    // wrap the function so we can return the oScope object when
    // the event fires;
    var wrappedFn = function(e) {
    return fn.call(scope, YAHOO.util.Event.getEvent(e),
    oScope);
    };

    For a while, at least for my events needs, I will not forget my own addEvent(), less than 1Kbyte, way faster than Yahoo’s.

    I like to think to addEvent/removeEvent as predefined Javascript primitives that every Javascript snippet should use,
    these primitives should change as less as possible the underlying environment and not rely on those changes if possible.

    These primitives should only do things they are meant to, thus attach one event handler at a time to an object.

    As an assertion to this concept, a long time ago I had in my addEvent (just an example):

    function addEvent(obj,type,fn){
    var i,ez;
    for(i in ez=type.split(’ ‘)){
    if(obj.addEventListener){
    obj.addEventListener(ez[i],fn,ec||false);
    }else if(obj.attachEvent){
    obj.attachEvent(’on’+ez[i],fn);
    }
    }
    }
    addEvent(document.forms[0].elements[0],’click keypress dblclick focus blur contextmenu’,someFunction,false);

    I mean somebody may need to attach the same event type to different objects as in Yahoo’s API, while somebody else may need to attach different event types to the same object as showed. For this reason I prefer to leave these task out of primitives and wrap some extra function arround them to achieve these same task.

    Multiple Event/Type Attachment, Multiple Object/Argument Reference and Scope Switching tend to make the code difficult to debug and ugly to read since parameter types are obfuscated, sometime they are object, some time array, some time string).

    Remember that we are making patches to the already existing functions just because one vendor refuses to follow the standards.-

    There would bee no mean/place for addEvent if all vendors agree and implement W3C suggested methods, and when that will happen
    it will be so easy to follow up for web-developers if these concepts are met.

    One thing worth notice is that Dean Edwards own addEvent() also has IE event reordering which is far more accurate than any other implementation and still the size is one tenth of YAHOO Event implementation.

    I don’t believe that a for/next loop to add a bunch of elements/handler pair in one shot is something SEXY or DOPING, also with code 10 times bigger…If I had to choose has an extra bonus I will prefer IE Event Reordering over Multiple Event Attachment, the latter everybody can do that.

    While on that I use the Web Developer Firefox extension by Chris Pederik and the wonderfull Leak Monitor extension by David Baron to help in finding bug/leaks in my code and I realized there where some warnings in the JSConsole so I looked at the code and could do
    these small changes. The ‘var notAvail=[];’ is the most notable and dangerous bit of this, while I am not sure of the ‘return true’ I added but somebody will correct me…

    And please if you have news about the Leaks let us know…

    — yahoo.js.orig 2006-05-03 09:14:28.000000000 +0200
    +++ yahoo.js 2006-06-07 02:08:33.000000000 +0200
    @@ -51,6 +51,7 @@
    YAHOO.log = function(sMsg,sCategory) {^
    if(YAHOO.widget.Logger) {^
    YAHOO.widget.Logger.log(null, sMsg, sCategory);^
    + return true;^
    } else {^
    return false;^
    }^

    — dom.js.orig 2006-06-07 02:11:54.000000000 +0200
    +++ dom.js 2006-06-07 02:47:57.000000000 +0200
    @@ -258,6 +258,7 @@
    var retry = function() { YAHOO.util.Dom.setXY(el, pos, true); };^
    setTimeout(retry, 0); // “delay” for IE resize timing issue^
    }^
    + return true;^
    };^
    ^
    this.batch(el, f, this, true);^

    — event.js.orig 2006-05-05 14:04:52.000000000 +0200
    +++ event.js 2006-06-07 02:46:34.000000000 +0200
    @@ -975,7 +975,7 @@
    delayedListeners = stillDelayed;^
    ^
    // onAvailable^
    - notAvail = [];^
    + var notAvail = [];^
    for (i=0,len=onAvailStack.length; i

  50. Dustin Diaz

    Diego, I’ll take a deeper look into your comment when I get a chance. Thanks for pointing this out.

  51. Diego Perini

    I submitted a bug report for the cleanups and memory leaks to Yahoo. But I still put an on hold to the Mem Leak problem. Seems that now I can’t reproduce them…Just updated Leak_Mon to 0.3.

    However now the order of event is screwded so I can not use YUI Events as a replacement.

    I just read Roman post (#27) about order of events in IE and where writing on his blog too. I am glad somebody else noticed this problem, really I do not understand how others do not clash with this problem…these two problems…

    The first beeing the RANDOM order in which will fire multiple events on the same elements if you use attachEvent.

    The second beeing you will run into problems with IFRAMES/FRAMES and possibly other elements if you don’t use attachEvent.

    It looks like old egg/chicken problem…

    Diego

  52. Phil

    Hi Dustin,

    Nice article. Bit of a noob question here:

    Event.addListener works really well for me when I pass as the first argument either and id (”el”) or a variable for an array of elements (array). However, when I use a simple var el = document.getElementById and try passing that (el) to the addListener, nothing happens!

    What am I missing?

    Thanks, and keep up the good work. Love your blog.

  53. Dustin Diaz

    @Phil: You need to actually get a real id.

    var el = document.getElementById('myId');
    YAHOO.util.Event.on(el,'click',myFunction);

    And that, I know works.

  54. Ashish

    Hi Dustin,
    Nice article. I use to think C++ was a complex language , but I was wrong. Everytime I search for something about javascript I learn something new. Maybe I am way behind.

    The demo was great.Did take bit of my time to understand (that $()…)

    And yes …you have a awesome website to.

    Regards,
    Ashish

  55. Infinit

    Very nice article Dustin!
    Was looking around for more information about the Yahoo UI, but this is a great explanation about how things work. Keep up the good work

  56. Schwarzenbek

    Thank you for the great information. Nice work.Greetings from Schwarzenbek Info

  57. Frederick C. Lee

    I’ve stumbled across YUI TreeView libraries to find a simple DOM treeview.

    I’m referring to YAHOO’s default treeview example:
    http://developer.yahoo.com/yui/examples/treeview/default.html?mode=dist

    I want to attach event listeners to each node of the tree.

    However I don’t get any response after (apparently) attaching events/node via addListener.

    Looking in the event.js, I noticed that the only DOM2 object is the Window itself. The nodes are considered ‘Legacy’ and are precessed within the useLegacyEvent and legacyHandlers.

    I lost the logic from there.

    Anyway, the addListener() returned TRUE, but nothing happened.

    The calling function is:
    if (!YAHOO.util.Event.addListener(node, ‘contextmenu’, handleClick)) {
    alert(”AddListener has failed. \n”+node);
    }

    Any ideas? Suggestions? Solution?
    ———-

    Also, I know of only event types: ‘click’ and ‘contextmenu’. Where can I get a list of event types?

    – Nice Write-Up, Keep up the good work.

    All is needed is a URL to a TreeView Guru!

    - Ric.

  58. Daniel

    Hey Dustin,
    thanks for posting those information. Really nice and high-quality stuff.
    Greetz,
    Daniel

  59. Phiro

    Hey, nice utility, thanks for this information ;)

  60. Mag

    How about developing similar utility, for Google and msn?

  61. daso4

    Excellent article, thanks a bunch!

  62. Webdesign Germany

    One thing worth notice is that Dean Edwards own addEvent() also has IE event reordering which is far more accurate than any other implementation and still the size is one tenth of YAHOO Event implementation.

    regards

  63. Afrika

    Great Article! Now using you method for event registration. Thank you!

  64. Plasma

    Really good, it is working perfectly for my needs.

  65. Webkatalog

    Looks like an interesting utilty. I will try it… thanks for the info!

  66. Jonas

    Thanks for sharing your information. Seems to work great.
    However, I am not sure if I am using it on my work - what
    about licensing?

  67. CableGuy

    Great work! Thank you. I am now using you method for my event registration.

  68. Webkatalog kostenlos

    I have tested the event utility and it seems to work great. I will considure including it in my upcoming project…

    regards, Edward

  69. Tottigol

    Yeah, that’s good. Nice and useful. Thank you.

  70. Artikelverzeichnis

    One thing worth notice is that Dean Edwards own addEvent() also has IE event reordering which is far more accurate than any other implementation and still the size is one tenth of YAHOO Event implementation.

    thank you for sharing this information
    Sandra

  71. Webverzeichnis

    Really good, it is working perfectly for my needs.

  72. Curt Leuch

    Great job and useful information, thanks a lot!

  73. Particletree » JavaScript Basics for Prototyping

    […] Forget addEvent, use Yahoo’s Event Utility - Diaz gives a thorough review of why Yahoo might have the best answer for dealing with event handling in JavaScript. […]

  74. Pension

    Nice work, i was looking for more information about the Yahoo UI, but this is a great explanation about how it works.

  75. Katalog

    Great tool, thanks a lot!

  76. Mode

    For me, it is working with no problems. Good Job and thanks.

  77. Heizung, Energie, Solar, Atom, Öl, Gas, Wasser, Luft

    Thx very much. everbody is posting news and tipps for google but yahoo information is rare. thx very much

    Heizung, Energie, Solar, Atom, Öl, Gas, Wasser, Luft

  78. Kent

    Excellent article and useful, thanks a lot!

  79. Heizung

    Good article, thanks:)

  80. Ison + Buddha

    Very nice article Dustin! Keep up the good work

  81. Pagerank

    Excellent article and useful, thanks a lot!

  82. Katalog

    Thank you for the great information. Nice work.Greetings from Germany!

  83. stefan

    Great work! Thank you.

  84. Webwelt

    Its a fantastic Article. Thanks it helps me a lot.

  85. Anzeigen

    Great job, it works perfectly for my needs.

  86. Webdesign Köln Group

    Great article. It really works, php and js together:) Thanks!

  87. Kfz Kennzeichen, Wunschkennzeichen

    Really? I can’t start it.. It dont work to me..

  88. Suchmaschinenoptimierung

    dustindaz, thanks to you, it’s what i needed!

  89. Anna

    A constructional guide and helpful informations.
    Much obliged from Germany!

  90. Bannerdesign

    Nice work, i was looking for more information about the Yahoo UI, but this is a great explanation about how it works.

  91. Skateboard

    Really good, it is working perfectly for my needs.

  92. Versicherung

    Looks like an interesting utilty. I will try it… thanks for the info!

  93. Dany

    We tested your ulity: It´s working very well!

  94. Dougi

    Its a fantastic Article. Thanks it helps me a lot.

  95. bibi

    Great article. It really works, php and js together:) Thanks!

  96. Chrissi

    Great and useful article, thanks a lot!

  97. ranking

    Nice work, i was looking for more information about the Yahoo UI, but this is a great explanation about how it works. ranking and pagerank

  98. partyband, tanzband

    I work with your script, perfect!

  99. Thommy

    I think PHP ist the coolest language of all!
    It’s very easy and powerful at the same time!

  100. Manga

    Really good, it is working perfectly for my needs.

  101. das88

    I have a question about the approach to gzipping the javascript. If you name your files *.php and rely on the header function to make sure the browser uses the file properly, will the browser still only fetch one file containing javascript at a time?

    Browsers are only supposed to fetch one javascript file at a time and some code relies on this fact by placing javascript include files in a particular order. How do browsers know, though, that a file contains javascript? Do they use the extension or the header? Do all browsers work the same way in this regard?

    I’ve seen other approaches to php gzipping javascript files (e.g. http://particletree.com/features/how-to-speed-up-your-textpattern-web-site/) where they first add a php application handler to *.js and then user header to let the browser know it is really a javascript file. This approach lets javascript keep the js extension.

  102. Dan

    @das88

    javascript and php are two totally different things. javascript is clientbased and php is serverbased. the clientbrowser never become php-code to work with thats the job of the server. javascript works only with the clientbrowser IF the browser supports javascript (many surfer deactivated it).

    sorry for my a little bit rusty english i`m from germany.
    greetings

  103. deutsche-statistik

    The only thing i can say: fantastic work - it works perfect. ty

  104. SEO Köln

    I’ve already tested it - it’s working!!! PHP is beautiful. Big-big-big thanks!

  105. newsartikel

    Respect man! really great stuff and the best of all: it works! ;-)

  106. Pablo Villas

    It seems to be very useful. I have been playing something around and it works. Thxs for sharing it, nice tool! Regards Pablo

  107. Martin

    Thank you, Dustin. The Yahoo Event model works well, and is a great stuff! Maybe I also love it, because PHP is one of the best languages!

  108. Japan Tuning Spoiler

    Very great article!

  109. Schokolade

    Graet article, good utility.

  110. Fussballvideos

    Thank you, great article dustin.

  111. Versand

    Very useful article, thank you.

  112. Pagerank

    @Versand or Schokolade:
    Damned this is not only a useful article this is a really excellent article about new possibilities in programming! fantastic dustin!

  113. kleinanzeigen

    great stuff dustin! thank u 4 sharing it.

  114. las-winwas

    absolutely great stuff dustin! i dunno much about javascript but it seems really powerfull, i think i have to learn much more about it. thank you!

  115. Stefan

    Thank you, Dustin. I’ve never heard of the yahoo script before. It seems to be very useful.

  116. osama

    The Yahoo Event model works well, and is a great stuff . I think PHP ist the coolest language of all & I work with your script, perfect!

  117. Pro-Ranking

    This looks like a time-saver. Alot of powerful features in one package. I no longer need to cobble event management puzzle together. Here it is!

  118. TM4B SMS Gateway

    Dustin,

    We really wish you updated your “top 10 javascript functions” post to include your statement “when I say forget addEvent, I mean any and every version of addEvent you can think of. This goes for Scott Andrew’s original addEvent function”.

    Would have saved us a lot of time!

    (Please note: We are truly appreciative of all your generous contributions!!!)

  119. Autogielda

    Looks like an interesting utilty, I will try it thanks !

  120. Daniel W

    Dustin, I admire your work here as usual. I have one question. Is it possible to use an event to find when a div is cleared of all its children. I have search results coming in that get appended to a div. The problem is that to clear the div from the old results I am looping through its children and removing each one. This is apparently too slow, because the new results get stacked onto the old ones. There must be a way to monitor when it is empty. Thanks for everything, I have learned so much from your site over the past few weeks.

    DanW

  121. katalog

    Maybe I am misunderstanding the reference to ‘this.swap’in the code example: ‘Assigning events to an array of objects’.

    I thought that the ‘this’ keyword related to the element that fired the event not the object that assigned it in this case ‘var cloner’.

    Can someone clarfiy how to add an event and reference the object that the attach event code is located in?

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

Flickr

Submit a Prototype

All content copyright © 2003 - 2007 under the Creative Commons License. Wanna know something? Just ask.

About | Archives | Blog Search

[x] close

Loading...

Submit a prototype

By checking this prototype I agree that I am not submitting false credentials, pornography, or a hate crime website. I also understand that by submitting my entry I may or may not be accepted, and if accepted, my entry may be taken down at any given time if I violate these terms.