Preface

Welcome to the YUI 3 Cookbook. If you’re already invested in the Yahoo! User Interface library (YUI), that’s excellent! This book is full of useful recipes and insights. Go forth and use it to build something great!

If you’re not already invested in YUI, that’s fine too. Perhaps you picked up this book because you like to stay informed. Or perhaps you picked up this book because you’ve been assigned to a project that uses YUI, you’re deathly afraid of this alien technology, and even now you’re idly wondering whether to rewrite the entire project from scratch.

Either way, you’re probably thinking to yourself, “What exactly is YUI good for?” Or perhaps even more accurately, “What can I build with YUI that I can’t just do with jQuery?”

The short answer is that with the help of auxiliary libraries such as Underscore and Backbone, there’s little you can’t build with jQuery. jQuery is an excellent document object model (DOM), events, and Ajax abstraction library, and people use it to build beautiful pages every day.

The longer answer is that every library is designed to address a particular set of problems. YUI focuses on keeping the complexity of web applications from spiraling out of control. Its key strengths are modularity and structure.

  • “Modularity” means that YUI is not a monolithic library, but a toolkit for assembling highly tailored libraries. If you need AutoComplete and Calendar, you can load just those widgets and leave out all the others. If you need DOM manipulation but not XHR requests, you can load just the core DOM APIs without Ajax. Modularity is not tacked on as an afterthought, but baked deep into YUI’s design.

  • “Structure” means that YUI’s APIs guide you toward building applications as a set of orderly components. Because of this, YUI components all have very similar behaviors. If you know how to work with a YUI ScrollView, you already know a lot about how to work with a Slider, a DataTable, or any other YUI widget.

The most realistic answer is that the best way to determine whether a framework or library works for you is to try it out yourself. YUI is a powerful open source JavaScript and CSS toolkit for building web applications, but there are many other fine choices out there. This book aims to demystify YUI and help you make an informed decision.

YUI 2 Versus YUI 3

To begin the demystification process, let’s start with the difference between YUI 2 and YUI 3.

YUI 2 burst on the scene at a critical moment, when the field of frontend engineering was starting to coalesce as a discipline. Even years after YUI 3’s release, many people still think of YUI as YUI 2.

YUI 2 code looks like this:

var nodes = YAHOO.util.Dom.getElementsByClassName('demo');

Although this looks uncomfortably like Java, bear in mind that back in early 2006, carefully namespacing your API under objects was a cutting-edge technique. The status quo was throwing your code into the global namespace and hoping for the best. Because of this focus on safety, YUI 2 gained a reputation as an industrial strength but verbose API.

YUI 3 launched in 2009 as a major revamp. The revamp not only baked modules and module loading into the core, but also cleaned up the API and eliminated most of the verbose method names.

YUI 3 code looks like this:

var nodes = Y.all('.demo');

which should look familiar if you are used to calling dojo.query('.demo'), $$('.demo'), or $('.demo').

However, thanks to ancient tutorials, rotting code examples, questionable “webmaster” forums, and other sources of bad advice, people who are vaguely aware of YUI often think it means long Java-esque method names. That’s unfortunate, because in YUI 3, the simple things are actually pretty simple. You can use YUI to manipulate the DOM and invoke page effects with very small amounts of code.

That by itself is not a reason to use YUI, as many libraries also provide powerful APIs for DOM manipulation and effects. Still, if you’re creating a quick prototype or a temporary marketing page with a couple of fades, rest assured that you can knock that page out with YUI just about as easily as with anything else.

Why Use YUI?

While YUI is succinct enough for “light” JavaScript work, where it really shines is in providing a solid foundation for more maintainable code.

As an example, say your boss asks you to design a form with a JavaScript date picker. You find a prepackaged widget that looks nice and seems to work well, so you copy and paste it into your code. Everyone is happy.

Then your boss tells you that the requirements have changed, and what the form actually needs is a double-pane calendar. So you hack that functionality into the widget. You manage to get it to work, but the code isn’t pretty, and worse, now you’re locked in.

To avoid lockin, every component in YUI is designed for extension. Every YUI widget shares the same solid API core and offers the same extension points, including a common rendering lifecycle with standard hooks to intercept or override. YUI lets you extend components in a classlike hierarchy, mix in new methods and properties, plug new behaviors into instances, and even inject arbitrary behavior before and after methods. In short, there is always a clean way to extend a YUI component instead of creating an unmaintainable mess.

While YUI is a very comprehensive toolkit, its overall “size” is as small or as large as you like. Nobody loads “all of YUI.” Instead, you load what you need: DOM manipulation, custom events, animations and page effects, Ajax, widgets, function and array utilities, templating, vector graphics, MVC—you name it, YUI probably has it.

And if YUI doesn’t have it, that’s no problem either. YUI is designed from the ground up to run safely alongside third-party code. You can even use the YUI Loader to wrap and load other libraries into the page as if they were ordinary YUI modules.

With this comprehensive toolkit comes comprehensive documentation and tools. YUI includes detailed user guides, tutorials, API reference documentation, hundreds of examples, and YUI Theater, an incredible video resource that documents the evolution of the frontend engineering profession. YUI also includes an entire suite of tools for professional code development: a builder, a documentation generator, a test framework and test runner, a minification and compression tool, and more.

As an open source project, YUI has accumulated a vibrant developer community. Most active YUI community members are experienced engineers who have a broad background with other frameworks and libraries. If you have technical questions about how to use YUI effectively, the community is a wealth of information.

Finally, YUI adheres to the bizarre, unfashionable philosophy that library code should, as much as possible, run as-is in a wide array of environments. This is actually a bit confusing to developers, who tend to assume that since there is no “YUI Mobile” fork of the library, that must mean YUI doesn’t work on mobile devices. In fact, the YUI team tests all library code on a wide selection of mobile devices, and adds methods and synthetic events to help you abstract away differences between platforms. Likewise, YUI runs in a Node.js server environment as-is. There is no YUI Mobile Edition or YUI Tablet Edition or YUI Server Edition. There is just YUI.

Library or Framework?

Web developers tend to call larger projects “frameworks,” and medium-size and smaller projects “libraries.” The line between the two is fuzzy, and tends to lead to religious disagreements. For a large but also highly modular project such as YUI or Dojo, the most accurate term might actually be “toolkit.” This book cheerfully refers to YUI as all three.

There is also a mini-trend of calling small JavaScript libraries “micro-frameworks.” However, this book will follow the last fifty years of software engineering practice and continue to refer to them as “libraries.”

Who This Book Is For

There are two main audiences who will benefit most from this book:

  • JavaScript developers who are new to YUI. These developers will most likely benefit from reading the simpler recipes (which tend to cluster at the beginning of each chapter) and from focusing on the “Problem” and “Solution” sections of each recipe.

  • JavaScript developers who have light to moderate YUI experience and are looking to deepen their knowledge. These developers will most likely be interested in the more advanced recipes and in reading the in-depth “Discussion” sections.

This book will not teach you JavaScript. It assumes that you are familiar with the basic mechanics of the language, up through and including prototypes, anonymous functions, and at least some standard ECMAScript and DOM methods. If you are an experienced engineer who picks up new languages in weeks, reading this book might help you learn some JavaScript through osmosis, but it isn’t the best place to start. A much better place to start is Eloquent JavaScript by Marijn Haverbeke (No Starch Press), followed by JavaScript: The Good Parts by Douglas Crockford (O’Reilly).

The reason this book assumes you already know JavaScript is that all libraries fail. There will be bugs. There will be situations where the library’s abstractions fall apart. Getting yourself unstuck means being able to understand what is going on both in the library code and beyond. Or as former Yahoo! architect Nicholas Zakas puts it, “Library knowledge is not frontend knowledge any more than knowing how to use a hammer makes you a carpenter.”

If you are already a YUI expert, this book probably covers a lot of familiar ground. Still, it might help you with corners of the library that you know less well, or provide some extra insight into why some aspect of YUI works the way it does.

This book is not a comprehensive reference manual for the entire YUI library. Some components are explored in detail. Some get short shrift. Many don’t get mentioned at all. Each recipe solves a specific problem, but very few cover every available method, parameter, and configuration option. For that, please consult the API reference documentation.

Resources and Community

YUI is released under a liberal BSD license and offers a wide variety of free resources. Its source code, documentation, ticketing system, and roadmaps are all out in the open. Some of the most useful resources include:

YUI library

The central hub for all things YUI 3, including downloads, examples, user guides, and reference documentation.

YUI on GitHub

The master source code repository for all projects under the YUI umbrella, available for forking and contribution.

#yui IRC on freenode.net

YUI’s official IRC channel, with many core YUI team members and prolific YUI community members available to answer questions. Alternatively, try the YUI library forums. The forums are often more useful for YUI 2 questions.

@yuilibrary and @yuirelay

@yuilibrary is YUI’s official Twitter account. @yuirelay is a Twitter bot that attempts to retweet items about YUI, the JavaScript library, without including items about Yui, the Japanese pop singer.

YUI Configurator

An online tool for calculating YUI module dependencies.

YUI Theater

An archive of video training and presentations curated over the last half decade. Some presentations cover general frontend topics rather than YUI-specific topics. The older videos are a fascinating record of the development of frontend engineering as a discipline. Also available as a YouTube channel.

YUI blog

Provides articles about new YUI releases, YUIConf, YUI Open Hours (a semiregular conference call to answer questions and solicit feedback), and even general frontend topics unrelated to YUI.

Online YUI Compressor

An online tool for safely minifying JavaScript and CSS with YUI Compressor. The online version is handy if you just want to try out YUI Compressor, but in a production setup, you should download and run YUI Compressor locally as part of your build system.

YSlow

A tool for analyzing general performance problems with web applications.

JS Rosetta Stone

A reference for switching back and forth between common tasks in jQuery and YUI 3. Maintained by Paul Irish and the YUI Team.

You can file bug reports and enhancement requests for YUI directly on the yuilibrary.com website. Follow the instructions under “Report a Bug”.

YUI accepts code contributions through GitHub’s fork/pull request model. To contribute a bug fix or feature enhancement to YUI, follow the instructions under “Contribute Code to YUI”. If you are new to Git, follow the instructions under “Set Up Your Git Environment”.

Conventions Used in This Book

About the Examples

The code examples in this book are deliberately very short. Each example focuses on solving a single problem or introducing a tiny number of new concepts, and most are short enough to take in at a glance. There are some longer examples, particularly in Chapter 7, but the vast majority are 15 lines of JavaScript or fewer.

All client-side JavaScript examples run in a very lean but valid HTML5 document that is some variation of Example 1:

Example 1. YUI 3 Cookbook boilerplate

<!DOCTYPE html>
<title>YUI 3 Cookbook boilerplate</title>

<div id="demo"></div>

<script src="http://yui.yahooapis.com/3.5.0/build/yui/yui-min.js"></script>
<script>
YUI().use('node-base', function (Y) {
    Y.one('#demo').setHTML('This is the YUI 3 Cookbook Boilerplate.');
});
</script>

The boilerplate is terse in order to keep focus on the JavaScript, while still providing a fully self-contained, runnable code example. Most examples will work from your local filesystem, but a handful must be run from a real web server. These are flagged accordingly.

Some recipes contain secondary examples that omit the HTML boilerplate and just show the JavaScript. In these cases, you can assume that the JavaScript is running in the same HTML document as the primary example.

All code in YUI 3 Cookbook is built to run against YUI 3.5.0. Keep in mind that YUI modules marked as “beta” can behave differently across minor versions of YUI 3.

All examples and related files in this book may be freely forked or downloaded from GitHub.

Typesetting Conventions

The following typographical conventions are used in this book:

Italic

Indicates new terms, URLs, email addresses, filenames, and file extensions.

Constant width

Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Also used for API, widget, and module names.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.

Tip

This icon signifies a tip, suggestion, or general note.

Caution

This icon indicates a warning or caution.

Using Code Examples

This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “YUI 3 Cookbook by Evan Goer (O’Reilly). Copyright 2012 Yahoo! Inc., 978-1-449-30419-5.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at .

Safari® Books Online

Note

Safari Books Online (www.safaribooksonline.com) is an on-demand digital library that delivers expert content in both book and video form from the world’s leading authors in technology and business.

Technology professionals, software developers, web designers, and business and creative professionals use Safari Books Online as their primary resource for research, problem solving, learning, and certification training.

Safari Books Online offers a range of product mixes and pricing programs for organizations, government agencies, and individuals. Subscribers have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technology, and dozens more. For more information about Safari Books Online, please visit us online.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at:

http://oreil.ly/yui3cookbook

To comment or ask technical questions about this book, send email to:

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments

This book would not have been possible without the hundreds of people responsible for the YUI project—the people who participated in the discussions, filed the bugs, issued the pull requests, and wrote the code that makes YUI what it is today. It is a great honor to have had the opportunity to write the first formal book for YUI 3. I only hope this book meets their expectations.

Thanks to all the wonderful people out in the greater YUI community who provided early review feedback: Pat Cavit, Jeff Craig, Chris George, John Iannicello, Todd Kloots, Subramanyan Murali, Anthony Pipkin, Kim Rowan, Robert Roy, Rich Tretola, Alberto Santini, Victor Tsaran, and Nicholas Zakas. Special thanks to Daniel Barreiro, one of the sharpest and most thorough technical reviewers it’s ever been my pleasure to work with.

I owe a great debt to the entire YUI team past and present for creating YUI, for shepherding it over the years, and for taking time out to provide me with deeper insights about how YUI works. Thanks to Thomas Sha, Eric Miraglia, Dwight “Tripp” Bridges, Adam Moore, Matt Sweeney, Derek Gathright, Allen Rabinovich, Satyen Desai, Jeff Conniff, Georgiann Puckett, Dav Glass, and Reid Burke. Much thanks to Jenny Donnelly for instigating this book and giving me the opportunity to write it; Luke Smith, my inside man in the YUI team; Ryan Grove and Eric Ferraiuolo for all their guidance; and Irene Lai, without whose generosity this project would have finished sometime in 2014.

Finally, a huge thank you to my editor, Mary Treseler, my parents, friends, and coworkers who offered so much support, and above all, my wife and best friend, Sarah. When I was trying to decide whether to take on this project, she was the one who said without hesitation, “Well, of course you should say yes.” Without her good humor, unwavering support, and willingness to patiently listen to her husband rambling on about JavaScript, this book would never have happened.

Get YUI 3 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.