The Yahoo User Interface is very extensive JavaScript library that enables a developer to easily create a next generation web application. Why am I using YUI? Well, as you know I like the Ext library, which was originally built as an extension to the YUI library. If you have worked with either Ext or YUI, you can pick up the other one pretty quickly.
Now, let me provide a little background with what I believe are the Pros and Cons of the YUI library.
Pros
- Fully documented, with a great API browser
- Very consistent and reliable
- Ease of widget interoperability
- Supported in several “A-Grade” browsers
- Unit testing framework
Cons
- Heavy page weight
- Verbose code (lengthy)
- Very few utility or helper functions/methods
Overall, I think that if you evaluate the yui library in the context of other libraries that I have used such as Prototype, jQuery, and Ext the 2.x generation of yui is lacking the coolness that the other libraries bring to the table. For example, implementing a sortable list in Prototype is super simple — a one liner. The equivalent code in YUI is several lines long (~100) to get similar behavior. Yui also lacks the use of chaining methods together like jQuery provides. Please don’t think I am bashing the yui library, its a fantastic javascript library that is very powerful, and the 3.x generation is looking like a nice improvement.
So, why use YUI? Because you can easily create a great looking web application that works seamlessly without needing additional JS libraries and plugins. Almost all the functionality you are looking to include in your next generation web application is right there. No need to go looking on Google for a Grid plugin, or a calendar widget — everything is included, and works together beautifully.
Lets see some code
OK, lets get started with the YUI library now that we have a little background.
This post will get you started with the YUI loader (to get the necessary JS files to the client) and the YAHOO.util.Event class.
YUI Loader
If you plan on creating an application that will depend on several of the YUI components, then the loader will simplify your life. The YUI loader handles dependencies, rolling-up the JS into a single file, and compression. Here is an exammple of the YUI loader:
1 2 3 4 5 6 7 8 9 10 11 12 13 | var loader = new YAHOO.util.YUILoader({ base: 'http://ajax.googleapis.com/ajax/libs/yui/2.6.0/build/', require: ['yahoo','dom','event','logger','animation','autocomplete','button','container','datasource','datatable','element','json','selector','paginator','tabview'], combine: true, timeout:10000, loadOptional:true, onSuccess: function(){ //create namespace YAHOO.namespace('webbiz'); YAHOO.lang.augmentObject(YAHOO.webbiz,webBizObj); YAHOO.webbiz.init(); } }); |
Above, I am specifying the YUI components to load from the Google Ajax APIs service. You can see that the array of components is not order dependent, remember that the loader will handle all of that for us. The onSuccess handler is the function you want to call after the necessary component have been loaded. Here, I create a custom namespace for my application, and then append (think of Objext.extend in Prototype) an existing object into this namespace.
YAHOO.util.Event
OK, so we have loaded YUI into the DOM, and we are ready to get started. One of the first components that you need to understand is the Event class in YUI. The event class abstracts the browser event implementations away, so you can rely on your events working across a majority of the browsers out there. So, what does this event class do? Here’s a quick rundown:
- Attaching events to one or more elements at one time
- Removing events from elements
- Scope correction
- Automatic cleanup
- Knowing when an element is available in the DOM
- Custom events
YAHOO.util.Event.addListener or YAHOO.util.on
The addListener method of the Event class allows us to append an event handler to an element, a critical component of keeping your javascript out of the presentation layer — unobtrusive JS. Here is a quick example:
1 2 3 | YAHOO.util.Event.addListener('myelement', 'click', function(){ this.style.display = 'none' }); |
The first argument is the element object, or the element ID. The second argument is the event type, which can include event types such as change, mouseover, mouseout, keyup, etc… The third argument is the function to call.
Scope declaration
The fourth argument is not used in this simple example above, but can be used to pass an object as the second argument to the callback function (the event object is the first argument). You can also use the fourth argument to specify the scope object, and set the fifth argument to true. Here is an example of ensuring the this scope within the callback function is set properly:
1 2 3 4 5 6 | function(){ this.name = 'Web Biz'; YAHOO.util.Event.addListener('myelement', 'click', function(){ window.alert(this.name); }, this, true); } |
Notice that the this scope in the example above no longer is the event’s currentTarget but the this scope of the outer function. When we click on the element ‘myelement’, we will get a JavaScript alert with the contents ‘Web Biz’.
Removing events
This one is quite simple, its just a matter of using YAHOO.util.Event.removeListener(), here is an example of removing all ‘click’ events from the element ‘myelement’:
1 | YAHOO.util.Event.removeListener('myelement', 'click'); |
Handler attachment deferral
This a neat feature of the YUI library that I don’t think exists in very many other libraries. If you call YAHOO.util.Event.on(’myelement’, …) and the element with an ID of ‘myelement’ doesn’t yet exist in the DOM, then it will periodically check for its existence, and once found will add the event handler. Note, this will not work if you pass the first argument as an element object reference instead of the string of the element’s ID.
Knowing when an element exists
This section goes along with the last one. YUI is great at knowing the state of the DOM, and allows you to prep your events before the element exists (think of declaring your event handlers before the Ajax call has returned and injected the html into the DOM).
There are several method included in YUI, including YAHOO.util.Event.onDomReady() which fires before window.onload but after the DOM is loaded (images and other assets might still be loading). YAHOO.util.Event.onContentReady() fires when an element and it’s nextSibling is also loaded. The most useful one, IMHO, is the YAHOO.util.Event.onAvailable() method. Here is a quick example of this method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | var myObj = { getStuff: function(){ this.attachEvents(); YAHOO.util.Connect.asyncRequest('POST', 'test.cfm', { success: function(t){ YAHOO.util.Dom.get('myelement').innerHTML = YAHOO.lang.trim(t.responseText); }, failure: function(){ window.alert('Oops, something went wrong. Give it another try.'); }, scope: this }); }, attachEvents: function(){ YAHOO.util.Event.onAvailable('mybutton', function(){ YAHOO.util.Event.addListener('mybutton', 'click', function(){ this.activate(); }, this, true); }, this, true); }, activate: function(){ window.alert('You clicked the button'); } }; myObj.getStuff(); |
Here, I have encapsulated some methods into an object myObj, and I am utilizing the scope correction features of the Event class to keep the this scope within my methods to the myObj object reference. Notice that within the getStuff() method, I am calling the attachEvents() method before calling my test.cfm file via Ajax. The ‘mybutton’ element doesn’t yet exist in the DOM, but I can be sure that once it does, it will have the event handler on the click event that calls the activate() method.
Hopefully this posting will give you a glimpse into the world of YUI, and encourage you to check it out and learn more about it. I hope to continue this with a series of posting about using YUI.

7 Comments, Comment or Ping
Chris Tierney
I also use YUI, however one annoying “bug” is the fact that a background image or color will stop at the page’s content height when using YUI’s grids. I had to convert a site to Google’s Grid to resolve this. This needs to be fixed to show a full page background and I haven’t found a fix for it. Have you run into this issue?
Jan 23rd, 2009
DRew
Any specific reasons to use this rather than jQuery (or others)?
Jan 23rd, 2009
brian
@Drew: Good question. With the jQuery UI library and QUnit, jQuery is a great choice, and I have used it for projects in the past and loved it.
So, why YUI? Here’s some compelling reasons imho:
- graded browser support
- lots of examples and good documentation (the api search is invaluable)
- backed by Yahoo!
- more components (no need to rely on 3rd-party plugins for things like data grids)
I’m not advocating for using YUI over jQuery or Prototype, just trying to share my experience of using the YUI library
Jan 23rd, 2009
brian
@Chris: No, I haven’t run into that issue. Is this a know issue, and if not, have you reported it to the YUI team?
Jan 23rd, 2009
Kumar
Yea, I have largely looked at YUI till now, and have played with Grids, Dom, Element, Button libraries the most.
Advantage over jQuery is, the important YUI libraries are available by default. For jQuery, its generally a plugin you are looking for (but the jQuery UI part should solve some of that).
I also think YUI due to excellent documentation and examples would be easier to learn for someone new to JS (like I am).
The other thing I like about YUI, is the provided skin itself is quite good and easily extended through documentation.
I also think the jQuery method chaining that a lot of people like, can prove confusing for a developer new to JS.
Jan 23rd, 2009
Nate Koechley
Hey,
@Chris Tierney - Sorry to hear you ran into problems! It’s not a bug exactly; here’s what’s happening (and sorry for not documenting this more clearly): YUI’s CSS Reset file sets the HTML element’s background-color to white. In nearly all browsers, when HTMLs background-color is set, then BODYs background-color only fills BODYs content area. And if BODY is shorter than the viewport, HTMLs background-color will fill the remainder of the viewport.
So, the best practice is to set the background-color on HTML when you want it to always fill the entire viewport, regardless of content length. No need to set it on BODY directly.
Hope that helps. If you have other questions, drop by http://yuilibrary.com/forum/ and I’ll be happy to help you out.
Thanks,
Nate (from the YUI team)
Jan 24th, 2009
Reply to “Getting started with YUI”