An Introduction to YUI

An Introduction to YUI

Tutorial Details
  • Topic: YUI, JavaScript
  • Difficulty: Beginner
  • Estimated Completion Time: 15 minutes

With jQuery dominating the JavaScript framework landscape, many newcomers aren’t exposed to other JavaScript frameworks. The truth is that there are a plethora of excellent JavaScript frameworks available, like MooTools, Prototype, Ext JS, and…YUI! While not as well known as some of the other libraries, YUI provides a wealth of tools for the web developer. Today, we’re going to take a quick tour of some of its features.


What is YUI?

YUI (short for Yahoo User Interface and pronounced Y-U-I) is an open source JavaScript and CSS library developed primarily by Yahoo.com. YUI includes JavaScript utiltiies, a CSS framework (reset, grid, and fonts), JavaScript widgets and tools to help include and manage your modules.

There are currently two supported versions of YUI. YUI 2, which was launched in 2006, contains the lion’s share of the YUI widgets. YUI 3 was released in 2009 and has a completely new syntax, greatly improving its ease of use (especially in event handling and DOM traversal).


Why YUI?

So you may be wondering, why should I even consider learning another JavaScript framework? Every framework has its strengths, so the one you choose will depend on your needs. Here’s a couple of things that YUI really has going for it:

  • An enormous library of widgets, including one of the most feature-complete datatables out there.
  • Stellar documentation – each component and widget has detailed instructions, examples, and api documentation.
  • Development Tools – YUI has a number of cool development tools including a profiler, in-browser console, and testing framework.
  • Flexible event handling with built-in support for touch and gesture events.

Ok, now that you’ve heard a little about YUI, let’s start looking at some code!


Including the Library

YUI allows for a lot of flexibility when it comes to loading the library; let’s look at a couple ways you can do it.

Method 1: YUI 3 Seed File

The seed file is the preferred way for getting YUI on your page. Just include the YUI seed file (only ~6KB), then include the modules you want via JavaScript. Let’s look at an example:

<script src="http://yui.yahooapis.com/3.2.0/build/yui/yui-min.js"></script>
<script>
YUI().use('node', 'anim','yui2-calendar', function(Y) {
    var YAHOO = Y.YUI2;
    Y.one('#test');
});
</script>

YUI.use() will make a request to get the required modules, and will pass you a YUI instance in the callback that has all of the required modules. YUI 2 components can also be included by passing in the module name, prepended by yui2-. If you include a YUI 2 component, then you can access the YUI 2 instance via Y.YUI2.

Method 2: YUI 3 Configurator

This web based tool allows you to pick the modules you need and allows you to download or link to a minified file with all of those dependencies (this is similar to the jQuery UI tool). It also provides stats as to how the files will affect page loads.

Method 3: SimpleYUI

SimpleYUI is a recently released tool that simplifies YUI inclusion for those who are used to just including a JavaScript library and having access to everything. Just include the SimpleYUI file and you’ll get a global YUI instance mapped to the Y variable with DOM manipulation, AJAX, and UI effects modules available.

<script type="text/javaScript"
 src="http://yui.yahooapis.com/3.2.0pr2/build/simpleyui/simpleyui-min.js"></script>

<script>
 //Y is a global variable set up by the SimpleYUI script.
 Y.one("#test").addClass("my class");
</script>

With SimpleYUI you can still use all of the other YUI modules dynamically by loading them with the YUI.use method.

Y.use('dd-drag', function(Y) {
    // set up drag and drop
});

SimpleYUI has the potential to really help YUI adoption because it makes it much more accessible and familiar to programmers coming from libraries like jQuery.


DOM Manipulation

DOM manipulation is very easy in YUI 3 and the syntax should be fairly familiar if you’ve used jQuery in the past.

YUI provides two methods for getting DOM nodes, via its Node module.

  1. Y.one(‘selecter’) – returns a YUI Node representing a DOM Node.
  2. Y.all(‘selecter’) – returns a YUI NodeList of all matches

Here’s an example.

// Y.one
var node = Y.one('#test-div'); // get me the node with the id test-div
var node2 = Y.one(document.body);  // Y.one also accepts a DOM element
Y.one('#my-list').get('id'); // my-list

// Y.all
var nodes = Y.all('#my-list li'); // all of my-list's list items

// chaining
var nodes2 = Y.one('#my-list').all('li'); // all of my-list's list items
var parent = Y.one('#my-list').get('parentNode'); // returns parent of my-list (as a YUI Node object)

YUI also provides a ‘test‘ method to see if an element matches a selector

var node = Y.one('#test-div');
// if node has the primary class
if(node.test('.primary')) {
	doSomething();
}

YUI also provides get and set methods to manipulate Node attributes, and convenience functions like addClass and removeClass.

// get and set
Y.one('#test-div').get('id');
Y.one('#test-div').set('innerHTML', 'Test Content');

// addClass, removeClass
Y.one('#test-div').addClass('highlighted'); // adds class to one div
Y.all('p').removeClass('highlighted'); // removes class from all p elements

Events

Events are attached using YUI’s on method. You can either call this method on a Node or on the YUI instance. For example:

// called on YUI instance
// myevent|click namespaces this onclick handler to myevent (used for removal later)
Y.on("myevent|click", function() { // do something }, "#test p"); 

// called on NodeList
Y.all("#test p").on("myevent|click", function() { // do something }); 

One interesting feature of YUI is that if you use the method from the first example, the selector does not need to immediately have a match. YUI will continue to poll for a match for up to 15 seconds after the page has finished loading, which means that you don’t have to wait for the document to be loaded to use it (you don’t have to wrap your event handlers in a document.load function).

Also notice that we prepended the event type with an optional string that namespaces the event. You can use this to later detach the event if you so desire.

Y.all("#test p").detach("myevent|click");

You can also simulate events…

Y.one("#test").simulate("click");

…and fire custom events.

Y.one("#test").fire("myevents:custom_event_one");

YUI 3 also supports touch events which allows you to add support to your JavaScript application for mobile devices. One potential gotcha is that you need to include the “event-touch” module using YUI.on in order for touch events to work.

Y.one("#test").on('touchstart', function() {
	// a touch event started
});

AJAX

AJAX requests are handled through YUI 3′s IO module. An AJAX call is made using the io function, as demonstrated below.

Y.io('/url/to/call', {
	// this is a post
    method: 'POST', 
	// serialize the form
    form: { 
        id: "my_form",
        useDisabled: true
    },
	// ajax lifecycle event handlers
    on: { 
        complete: function (id, response) {
            var data = response.responseText; // Response data.
        }
    }
});

The IO method accepts a URL and a configuration object as parameters. The configuration object is highly configurable, but I’ve included a couple of the most common options in the above example.

  1. method – what HTTP method to use
  2. form – if this option is specified, the form with the given id will be serialized and passed with the request.
  3. on – this object sets up event handlers for various stages in the request lifecycle.

YUI’s io module also allows you to send cross domain requests using a Flash based file provided by Yahoo. There are some caveats, however. First, you must have a copy of the YUI flash file on your server to actually make the request, and second, the domain you are accessing must have a cross-domain policy file that grants you access.

Y.io('http://www.somedomain/web/service/', {
    method: 'POST', 
    data: 'data=123',
	// use flash
	xdr: {
		use: 'flash',
		dataType: 'xml'
	}	
	// ajax lifecycle event handlers
    on: { 
        complete: function (id, response) {
            var data = response.responseText; // Response data.
        }
    }
});

JSONP is also supported, but through the YUI JSONP module, not the IO module.

Y.jsonp(someurl, function(response) {
	// handle jsonp response
});

One more module that is quite useful in conjunction with AJAX is the JSON module. This allows you to easily parse AJAX request which return JSON. JSON can be parsed using the JSON.parse method

var obj= Y.JSON.parse(response.responseText);

Animation

YUI 3 contains an animation module that can be used to perform pretty much any kind of animation. The syntax is a good bit different than jQuery’s, so let’s take a look.

Animations occur in a couple of steps in YUI. First, you set up a new animation object that describes your animation, then you run it.

    // animate a div from no size to a height and width of 100
	var animation = new Y.Anim({
	   node: '#my-div',  // selector to the node you want to animate.
	   // values to animate from (optional)
	   from: {
	      height: 0,
		  width: 0
	   },
	   // values to animate too
	   to: { 
	      height: 100,
		  width: 100
	   },
	   duration: 0.5, // set duration
	   easing: Y.Easing.easeOut // set easing
	});
	
	animation.run();

All of the properties can be changed using .get() and .set() on the animation object, allowing you to change the animation or the DOM elements to animate. Animations also fire events that can be listened too.

	// animation is a Y.Anim object
	animation.on('end', function() {
		// fired after animation finishes
	});

Taken together, the YUI animation object can be used to create all kinds of animations in you application.


Widgets

One of the nicest features of YUI is its widgets. YUI 3 currently has a limited set of widgets (tabs, a slider, and an overlay to name a few), but provides a powerful framework for creating your own YUI 3 widgets. YUI 2, on the other hand, has an enormous library of widgets. Here are a few:

  • DataTable – a complete data table widget with ajax loading and pagination, editable cell support, resizable columns, and progressive enhancement.
  • ImageCropper – a widget that helps with image cropping.
  • LayoutManager – widget to make complex layouts via JavaScript.
  • Calendar – a popup calendar widget.

There are many more widgets that you can use, and you can find them all at the YUI 2 developer website

.


CSS Libraries

The last component that we’re going to take a quick look at is the YUI CSS libraries. YUI 3 provides four CSS resources.

  • CSS Reset – basic CSS reset rules. Everyone has their own idea of what a reset file should do, so you may or may not like this one.
  • CSS Base – these styles build on the Reset styles to provide consistent rendering across all supported browsers. This file provides things like input styles, header sizes, and table styles.
  • CSS Fonts – normalizes font sizes across all supported files. Once this stylesheet is applied, font-sizes are changed using percentages according to a table YUI provides. The YUI CSS Fonts resource is used by the popular HTML5Boilerplate.
  • CSS Grids – a CSS grid framework to help with layout. I’m not a fan of grids in general, but if you’d like to learn more, Andrew Burgess has a nice writeup of this one on Nettuts+.

Conclusion

This was only a quick look at a few of the components and modules that YUI offers. If this article has piqued your interest, I recommend that you head over to the YUI developer documentation and find what else YUI offers. What are your impressions? If you’ve used YUI in the past, what do you think of it?

Tags: YUI
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.andrewwooldridge.com/blog Andrew Wooldridge

    Great article! Glad to see more folks discovering YUI. I’d love to see what you write as a followup!

    • Sana

      I agree with u !!!

  • http://www.diigital.com Mike Healy

    YUI is also lets you load only the components you need. If you’re just doing something simple and only require event handling and DOM manipulation that’s all you need to load. jQuery can be overkill in some situations.

  • http://david-tang.net David

    Great article! I like how this cleared up a lot of questions I had about including the library onto the page. I was confused on this since there were so many different ways. Coming from jQuery, I am used to just including one or 2 files. The syntax feels so much like jQuery.

  • bpr

    NIce article, however, I would like to know why I should use YUI instead of jQuery or any other one ? Are there some key features where you can say: this the one! That feature makes the difference. Would have been nice if you did that. But anyway. Nice introduction. Gives a quick overview and is definitely useful for a YUI kick off.

    Well done

  • Sahan

    It’s about the framework + the community. When more people use it the community + support becomes stronger :)

    • http://www.petarzivkovic.com Petar Zivkovic

      Exactly!

      The more people using a framework, the easier it is to get help when you are stuck on a complicated (or simple) problem.

  • Karl G

    @bpr:

    There are a couple benefits to using YUI3. The main reason I use and recommend it is for the component architecture and dependency management/loading. If you’re not actually building apps client side, the main benefits are trivial access to community addons through the gallery (e.g. you can pull in the yui version of the jQuery quickstand plugin by simply adding ‘gallery-yuisand’ to your YUI.use call) and that yui widgets are one of if not the highest quality widgets available in a js library, e.g. a search for ‘introducing yui3 autocomplete’ should get you Ryan’s recent 150 (!) slide presentation on the autocomplete widget coming in 3.3.

    On components:

    jQuery works great until you try to build an app with it. If you follow standard jQuery practices sites start getting more difficult to maintain roughly when you cross the 1k lines of code threshold. This is due to the page-centric way most jQuery code is structured, you start getting almost-duplicate behavior on different pages, copy/paste code happens, etc. There are ways around this, usually by using a KVO/MVC framework or by refactoring your site as a number of plugins, you can keep things under control, but you have to know to do this so the vast majority of jQuery codebases I’ve run into are a mess.

    YUI’s event and component system provides a blueprint for how to chop an application up into reusable pieces and structure your code in order to keep complexity under control as the app grows. You build modules, expose their state with ATTRS, expose behavior through events, and pull them in with YUI.use. Since jQuery introduced events in 1.3, you CAN do this in jQuery and I have, but you have to figure out how to modularize the app (I recommend backbone) and handle dependencies (requireJS).

  • http://www.aviank.com Anky

    look like i should explore it more.. implementing datatables looks pretty easy. Thanks for sharing it

  • Jason

    Fix your last link.

    • http://www.ssiddharth.com Siddharth

      Fixed, thanks!

  • http://websitecenter.ca/ Iouri Goussev

    I’ll check yui, it looks like it makes your code more modular compared to jquery.

  • http://www.monkey-house.ca Greg

    Wow, YUI was always sort of in the back of my mind as a “research this later…” kind of thing. But the way you clearly explained how to include the different modules, as well as comparing selector syntax to jQuery (making it more familiar and accessible for numpties like me) just pushed it right into my list of things to try out immediately. I have a project that would have gotten the typical jQuery treatment, but I think I’ll give YUI a shot now. Simplified namespacing of events, and the 15 seconds of polling for handlers…. to me those are two differentiators right away.

  • http://beben-koben.blogspot.com Beben Koben

    I do not understand about this, I received the finished product only…hihihihi :D
    thanks Bos^^

  • http://hyperlexic.com hyperlexic

    …and after you have built your app using this library, Yahoo will announce they are shutting it down and that you can go cram it with walnuts. i don’t see how any developer can trust their application to yahoo’s seemingly arbitrary reasoning for closing down good, valuable and still relevant services.

    feh – FEH! i say to you yahoo.

  • http://reidburke.com Reid Burke

    @hyperlexic

    As an engineer on the YUI team, I can say YUI is becoming even more important within the company. Our homepage, Flickr and countless other large, profitable sites on our network benefit from our team’s in-house expertise, which the YUI community in turn benefits from in every frequent release.

    Every single YUI project—down to our build system—is BSD licensed and the full source code history is clonable on GitHub. Every engineer on the YUI team is committed to our products, which isn’t something any one entity can ever take away.

    In short: we <3 you.

  • http://www.techonia.com Fuad NAHDI

    thanks for the tutorial, that gives me deeper understanding about YUI.

  • http://twitter.com/timlind Tim

    That was a great overview to the framework. Concise documentation that gets straight to the important parts which help you decide is hard to come by.

    I would really like to see you expand on this here and include some more detail to help people decide. For example, how the event utility works (especially for custom events), and how the library helps us create our own widgets (especially in comparison to other libraries).

  • http://forgetdbigwords.com Okeowo Aderemi

    Am Glad to see YUI and Not Jquery for a change but Nettuts hasn’t Covered Dojo, cuz i feel Dojo is Quite Good to But thanks for the Tutorial.

  • http://www.dwmultimedia.com.mx Francisco Vazquez

    Excelent POST!!!, i used YUI once and it was a little bit confusing, it was the first or second version, i dont remember.

    I’ll download the latest version of YUI and test all the features it has.

  • http://digital-checks.blogspot.com/ digital money doctor

    intersting site

  • http://onore.kiev.ua Onore

    What about support html5? And What new will be at YUI 3,5?