Architecture & DesignWhat Can the Yahoo! User Interface (YUI) Library Do for Your Site?

What Can the Yahoo! User Interface (YUI) Library Do for Your Site? content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

In this article, I will look at the Yahoo User Interface (YUI) library in more detail. The YUI is an AJAX framework, but it is also a generic JavaScript library that provides a lot of Web 2.0 widgets or UI elements, effects, and tools for web developers.

Introduction to the YUI

The abundance of AJAX frameworks on the market make it very hard for one of them to get noticed. But what better way is there than if it’s used by one of the most popular web sites online? And, the YUI is currently used on a lot on the Yahoo web pages, including the main front page, my Yahoo portal, Yahoo news and Yahoo finance. Because Yahoo’s main business is web based, their acceptance and usage of the YUI accomplishes two things. First, it get the library noticed and second, it proves that it’s mature and stable code.

The library was released as open source under the BSD license. This means that it can be freely used for commercial projects, and it is currently maintained by the Yahoo developer community.

The YUI is written entirely in JavaScript, similar to or Dojo. Its installation (which I’ll cover further), simply involves inclusion of several JS files on the page. The YUI has some of the best documentation available for an open source project, and it is clearly evident that the company spent a lot of time putting together examples and tutorials for every widget and functionality available. Every component is fully described and comes with several examples that are easy to understand. YUI code is also cross-browser compatible and supports all major browsers.

The YUI library can be conceptually separated into three parts. The first part is the AJAX communication wrapper that YUI calls Connection Manager. This utility deals with the instantiation of the XmlHttpRequest object, handling of the AJAX requests, browser status codes, and callback mechanics. The Connection Manager is reused in a lot of other widgets, making then AJAX-enabled. The second part of the YUI is a very solid collection of UI widgets such as Calendar/Date Picker, TreeView, TabView, and so forth. And, the last part is a polished collection of DHTML utilities that simplify DOM scripting and the creation of arresting visual behaviors, such as Drag & Drop or Animations effects. The utilities include the Document Object Model (DOM) manipulation package, CSS, Font, Event utilities, and others.

I should also mention that all YUI widgets come with separate CSS files. Changing their appearance to match the custom look of a particular site is easy; you don’t have to touch the JavaScript code.

Setting Up the YUI

To set the up YUI, download it from the Yahoo Developer Network, unzip it into your web server directory, and include the JavaScript files corresponding to the features you want to use in your pages. For example, if you want to use Drag and Drop, you may include these JavaScript files.

<script type="text/javascript" src="../../build/yahoo/yahoo.js" >
<script type="text/javascript" src="../../build/event/event.js" >
<script type="text/javascript" src="../../build/dom/dom.js">
<script type="text/javascript" src="../../build/dragdrop/dragdrop.js" >

Similarly, if you want to use Calendar/Date Picker, you can include it.

<script type="text/javascript" src="yahoo.js"></script>
<script type="text/javascript" src="event.js" ></script>
<script type="text/javascript" src="dom.js" ></script>
<script type="text/javascript" src="calendar.js"></script>
<link type="text/css" rel="stylesheet" href="yui/calendar.css">

Unlike, which requires that you include one core file and dynamically load other modules, the YUI requires an explicit declaration of what you need.

As an alternative to including required JS files from the local web server directory, the same files can be included from the Yahoo servers. From the client point of view, there is no difference from where the file is downloaded, either from your server or the Yahoo server. Also, note that all library files come with three versions: the regular file, file with the .min and .debug in its name. Any library file with the .min in its name is minified, meaning that comments and white space have been removed to make them more efficient to download. For example, calendar-min.js and similarly .debug uses the debug version of the file; for example, calendar-debug.js.

AJAX Connection Manager

If you are not using the YUI, the only way to initiate an asynchronous AJAX call to the server is to write something like this:

function getXmlHttpObject() {
   var XHR=null;
      if (window.XMLHttpRequest) {
         XHR =new XMLHttpRequest();
      else if (window.ActiveXObject){
         XHR =new ActiveXObject("Microsoft.XMLHTTP");
      return XHR;

This code checks for different browser implementations of the XMLHttpRequest object, and hopefully is compatible with most browsers. You also will need to use XHR object’s API to send GET or POST request and then manually check for any error codes, such as 404 “page not found” and status codes. It completes such a response in a total of over 30 lines of code.

With the YUI’s Connection Manager, all of this plumbing has been already implemented. All you need is one line of code:

var transaction =
   YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);

Note: The callback is not a function but an object, and the asyncRequest method returns a reference to the transaction that can be used later. This method supports the GET, POST, and HEAD options of the HTTP request. The URL parameter is self explanatory.

The callback object is simply a JavaScript object that has a code definition of the methods you want to execute on a successful response or a failed response. It can also have other options, such as timeout value, arguments, and scope.

var callback = {
   success function(o)  {/*success handler code*/},
   failure: function(o) {/*failure handler code*/},

Here is how a form would be submitted:

var formObject = document.getElementById('aForm');
YAHOO.util.Connect.asyncRequest('POST', '',

Finally, if you want to terminate a request that hasn’t completed in ten seconds, you can set a timeout variable in the callback object to 10000 or call the abort method and pass in the transaction variable.


The YUI Connection Manager also supports asynchronous file uploads, which are specified with an argument array in the callback object. For example:

var callback = {
   success: function(o) {/*success handler code*/},
   failure: function(o) {/*failure handler code*/},
   argument: ['file1','file2']

There are more options in the Connection Manager, but these are the main use cases. Now that you know how to initiate an asynchronous AJAX call with YUI, look at what other neat effects and utilities are available.

Drag and Resize with YUI

As you have noticed, the amount of code that is required to achieve powerful things with YUI is not that large, and this is true for widgets, effects, and utilities as well. For instance, the total fade to white effect can be done with this code:

init = function() {
   var anim = new YAHOO.util.Anim(id, { opacity: { to: 0 } },
                                        1, YAHOO.util.Easing.easeOut);
   YAHOO.util.Event.on(document, 'click', anim.animate, anim, true);
YAHOO.util.Event.onAvailable('id', init);

where id is the ID of the element you want to fade as soon as page loads and it is available. The drag effect can be created by calling one line, new YAHOO.util.DD("id"), where id is also the element you want to make draggable.

Say that, besides being able to drag an element across the screen, you also want to make it resizable. This does require a little extra work, but as you will see, the YUI helps a lot. Here is a simple DIV element with a small blue icon in the lower right corner.

The DIV does not look very special, but it features two powerful concepts: drag and resize. (The actual demo is part of the source code.) Clicking and holding the mouse on the gray rectangle will move the DIV and clicking and holding over the blue corner will resize it. Here is the code needed to implement Drag and Resize logic.

Includes for the required JS files:

<script type="text/javascript" src="../../build/yahoo/yahoo.js" >
<script type="text/javascript" src="../../build/event/event.js" >
<script type="text/javascript" src="../../build/dom/dom.js">
<script type="text/javascript" src="../../build/dragdrop/dragdrop.js">

The HTML code is trivial, and just defines the two DIVs: the outer panelDiv and inner blue handlerDiv

The JavaScript code looks a little confusing, but is actually plain JavaScript with JSON type definitions of objects and some logic to calculate size of the outer panelDiv relative to the handleDiv (on the mouse drag of handleDiv).

The DDResize object (note that functions are objects in JavaScript) is defined, and set to extend from the YAHOO.util.DragDrop

YAHOO.extend(DDResize, YAHOO.util.DragDrop);

The default Drag and Drop behavior from the parent objects—prototype.onMouseDown and prototype.onDrag—is overwritten with custom logic, to change the outer panelDiv size as the inner handleDiv is moved.

A new window onload listener is also defined to invoke the drag and resize behavior on assigned DIV elements:

YAHOO.util.Event.addListener(window, "load", DDApp.init);

And, the new behaviors are assigned with the callback object DDApp, which initializes DDResize, and also initializes the default YUI YAHOO.util.DD object.

new DDResize("panelDiv", "handleDiv");
new YAHOO.util.DD("panelDiv");

As I mentioned earlier, the DD object has the actual Drag & Drop implementation where the linked element follows the mouse cursor during a drag. If only a drag was all that required, no extra logic would be written, but the resize is custom and not part of the YUI. Again, the first parameter to the DD is the ID of the element to be dragged. The outer panelDiv (with inner handleDiv) will be dragged when the mouse is over it, and resized when the mouse drags the inner handleDiv.

Here is the CSS look-and-feel definition for the two DIV elements:

Note that inner handleDiv is absolutely positioned inside the outer panelDiv, which has a relative position. As you can see by adding a few lines of YUI code, any element can be made drag enabled, and by adding a small amount of custom code, any element cam become resizable too.

The Drag is just one of the examples of included utilizes. Other utilizes include fine-grained Event handing, back button utility, or manipulation of the DOM structure.

YUI Widgets

The YUI comes with a rich set of pre-built widgets, and implementing them also takes very little coding. Widgets such as Sliders, Grids, DataTables (with inline editing), Calendar, TreeView, and Tabs let developers easily incorporate advanced features into their projects.

And, if all of this was not enough, there is also a generous library of animation effects that can be mixed and matched to create an infinite number of possible outcomes, applicable to any visible DOM element. One neat effect that I have not seen in other frameworks is the auto scroll effect of the text inside of the textarea, either vertically or horizontally.

Download the Source Code

Download the source code for this article here.


In this article, I have covered the Yahoo User Interface (YUI) library in some detail. The YUI currently competes with other AJAX frameworks, such as Dojo, Backbase, or Even though it is a free product, it has great documentation, examples and a lot of features. If you are looking for a solid AJAX framework to help with rich user interface development or just want to code some AJAX, the YUI can be a great start. It also will be interesting to see how the YUI evolves in the future and what features Yahoo or the open source community will introduce into it.


About the Author

Vlad Kofman is working on enterprise-scale projects for the major Wall Street firms. He has also worked on defense contracts for the U.S. government. His main interests are object-oriented programming methodologies, UI, and design patterns.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories