Video icon 64
Learning to code? Skill up faster with our practical video courses. Start your free trial today.
Advertisement

An Introduction to YUI

by

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?

Advertisement