http://www.developer.com/

Back to article

10 Cool Things You Can Do with JavaScript and YUI


October 25, 2007

1. The YUI

The Yahoo User Interface (YUI) library is a collection of JavaScript and CSS resources that make it easy to build a wide variety of interactive web pages. It also includes easy-to-use widgets that can be directly dropped into a page.

YUI not only handles the cross-browser challenges for developers, from JavaScript to font sizes, but it also includes CSS that can be included to minimize the time to implement a widget. In addition to JavaScript and CSS, the library also includes test scripts, examples, and documentation for YUI components. Using YUI, you can minimize your effort to create a feature rich web interface.

2. Manipulating the DOM

Creating interactive interfaces on the web requires interacting with the Document Object Model. It's okay if you don't have the innermost knowledge of the DOM because YUI does a lot of this work for you in one of its core libraries.

The YUI DOM class offers convenient methods to access DOM elements. This library is a singleton and doesn't require instantiation. Simply put, just include the prerequisite yahoo.js and the library, dom.js, and call the methods directly.

You can do a lot using the DOM Collection library, including easily accessing page elements for manipulation. You also can get and set styles, the XY coordinate of an element, manipulate class names, and even get the Viewport size.

The DOM library is probably most often used to retrieve page elements by either ID or class for manipulation. You also can shorten your code by assigning this singleton object to a variable at the beginning of a function or class. You can do this with almost all of the YUI utility classes.

$D = YAHOO.util.Dom;

This allows you to call any method of the DOM class using a much shorter line of code throughout your function or class.

$D.get('myid');

3. AJAX Requests

There are a lot of AJAX libraries these days. YUI's AJAX implementation has a lighter footprint than some other libraries. The Connection Manager class handles AJAX requests in YUI. It provides a simple but powerful interface while handling cross-browser instantiation of the XMLHttpRequest, handles' states, and server responses.

To use the Connection Manager, include the prerequisites Yahoo and Custom Event, and then the Connection Manager.

<script src="="../yui/build/yahoo/yahoo.js"></script>
<script src="="../yui/build/event/event.js"></script>
<script src="="../yui/build/connection/connection.js"></script>

When you want to handle a response from an AJAX call, create a callback object to handle the server response and the returned data. If you don't care what information comes back from the server, you can omit the callback object.

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

The response object is passed into each function in your callback object. If you need to pass in additional objects, numbers, strings, or arrays to your callback methods, you can do this by using the optional argument member.

Each of these members is optional. The Connection Manager will automatically call either success or response member functions depending on the server response. Each of these members is optional because you are overriding the callback object in the Connection Manager and passing in a custom methods for handling the response. If there is no response method defined in your code, nothing happens.

To make an AJAX request, you also need to define the data you want to send to the server, the URL to send the data to, and the method to use. In this example, you'll use the following URL, URL param string, and the HTTP POST method. If the data string has special characters, you would need to encode the postData string.

var sUrl     = 'http://myserver.com/ajax_url';
var postData = 'username=anonymous&password=blank';
var myMethod = 'POST';

At this point, you have defined methods defined to handle success and failure, your designation URL, your POST data string, and your HTTP method. Now, you just need to make your AJAX request using the Connection Manager. Use the asyncRequest method of the Connection Manager to query the server.

var request = YAHOO.util.Connect.asyncRequest(myMethod, sUrl,
   callback, postData);
Note:
You also could retrieve a form element from the page by using the DOM class and pass the form object in to the Connection Manager.

4. Drag and Drop

Drag and drop is a cool effect that interacts with the DOM of a web page. It's been gaining popularity over the last few years, cropping up in shopping carts and other interactive interfaces.

Creating drag and drop interaction is easy using the DragDrop library in YUI. To create this effect in YUI, first include the Yahoo DOM Event and the DragDrop classes in the head of your HTML document.

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

Then, add an element to the page that you want to drag and drop.

<div id="element1">
Drag &amp; drop this element around the page.
</div>

Finally, instantiate the DragDrop object.

var dd1 = new YAHOO.util.DD("element1");

5. Displaying Tabular Data on a Web Page

At some point, almost everyone needs to represent tabular data on a web page. The DataTable control provides a simple but powerful way to display tabular data on a web page. This YUI widget also offers interactive features including sortable and resizable columns, row selection, pagination, scrolling, and inline editing.

The DataTable control is dynamically marked up as a table, with a <thead> and two <tbody> elements. The <thead> is populated by the ColumnSet class and the <tbody> relies on the DataSource, RecordSet classes and DOM UI.

The DataTable has quite a few prerequisites, but don't be intimidated. Once you're set up, using the DataTable in your web page is pretty painless. You can use the included CSS to style the data table, without worrying about browser display issues. Dependancies are contingent upon the features you want to include. For instance, resizable columns require the DragDrop library and AJAX requires the Connection Manager. More information on the various features of the DataTable widget is available in the YUI documentation and examples.

<link type="text/css" rel="stylesheet" href="/build/datatable/
   assets/skins/sam/datatable.css">

<!-- Dependencies -->
<script type="text/javascript" src="/build/yahoo-dom-event/
   yahoo-dom-event.js"></script>
<script type="text/javascript" src="/build/element/
   element-beta-min.js"></script>
<script type="text/javascript" src="/build/datasource/
   datasource-beta-min.js"></script>
<!-- OPTIONAL: Connection (enables XHR) -->
<script type="text/javascript" src=" /build/connection/
   connection-min.js"></script>
<!-- Source -->
<script type="text/javascript" src="/build/datatable/
   datatable-beta-min.js"></script>

A table is useless without data, so you first need to define the data that will be used for the table. Do this by instantiating a DataSource object that will contain your data for the rows in the table.

YAHOO.example.fruit = [
   {name:"Plum",price:"$2.50"},
   {name:"Fig",price:"$3.50"},
   {name:"Orange",price:"$3.99"},
   {name:"Apple",price:"$2.00"}
];

Instantiation of the DataSource object is, of course, done by calling the method 'new' on the DataSource utility class. The first and only argument to 'new' is the data structure for the class uses to build the object. In this case, the argument is the array Yahoo.example.fruit.

var myDataSource = new YAHOO.util.DataSource(YAHOO.example.fruits);

You also could use JSON, XML, Text, or a HTML table but for this example, use a JavaScript array to keep things simple.

Next, you need to set the responseType and define your responseSchema for your DataSource object. Because you're using a JavaScript array, set the responseType to TYPE_JSArray. The responseSchema defines the names of the columns the object will receive.

myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
myDataSource.responseSchema = {
   fields: ["name","price"]
};

Now, you can instantiate the DataTable object. All you need to pass in is an ID or element reference of a DIV element that will act as a container for the DataTable, the column definitions, and the newly created DataSource object.

var myColumnDefs = [
   {key:"name", label:"Fruit Type"},
   {key:"price", label:"Price"}
];

var myDataTable = new YAHOO.widget.DataTable("myContainer",
   myColumnDefs, myDataSource);

As you can see, the keys for the column definitions match the fields defined in our responseSchema. The labels in the column definitions are used in the markup for the table for the visible table headers.

You also could pass in a forth parameter to the DataTable object containing configuration options. There are a lot of options to the DataTable control in YUI. Again, I would highly recommend reviewing the examples and documentation to see the full list of options and features for this widget.

5a. Pagination

One of the features of the DataTable widget that I find most useful is pagination. Pagination makes interaction with large datasets much easier for the end user and keeps the design of a page intact.

Pagination also occurs without page reloads and the pagination elements are configurable. A user can choose how many rows to show on a page and easily access other pages in the DataTable.

// Configure pagination features
// The following object literal reiterates default values
var myConfigs = {
   paginated:true,         // Enables built-in client-side pagination
   paginator:{             // Configurable options
      containers: null,    // Create container DIVs dynamically
      currentPage: 1,      // Show page 1
      // Show these in the rows-per-page dropdown
      dropdownOptions: [10,25,50,100,500],
      pageLinks: 0,        // Show links to all pages
      rowsPerPage: 100     // Show up to 100 rows per page
   }
};
var myDataTable = new YAHOO.widget.DataTable("myContainer",
   myColumnDefs, myDataSource, myConfigs);

6. Rich Text Editor Widget

The Rich Text Editor widget was just added to YUI in version 2.3.0. The YUI editor is cross-browser compatible and includes a lot of the standard features you would expect for a simple text editor.

<!-- Skin CSS file -->
<link rel="stylesheet" type="text/css" href="../yui/build/assets/
   skins/sam/skin.css">

<!-- Utility Dependencies -->
<script type="text/javascript" src="../yui/build/yahoo-dom-event/
   yahoo-dom-event.js"></script>
<script type="text/javascript" src="../yui/build/element/
   element-beta-min.js"></script>

<!-- Needed for Menus, Buttons and Overlays used in the Toolbar -->
<script src="../yui/build/container/
   container-core-min.js"></script>
<script src="../yui/build/menu/menu-min.js"></script>
<script src="../yui/build/button/button-beta-min.js"></script>

<!-- Source file for Rich Text Editor-->
<script src="../yui/build/editor/editor-beta-min.js"></script>

The Rich Text Editor has been designed to replace an existing HTML <textarea> element. If users try to use the Rich Text Editor without JavaScript support, they will simply see a standard <textarea>.

Here's the basic markup for the text area, straight from the YUI documenation.

<body class="yui-skin-sam">
<textarea name="msgpost" id="msgpost" cols="50" rows="10">
   <strong>Your</strong> HTML <em>code</em> goes here.<br>
   This text will be pre-loaded in the editor when it is rendered.
</textarea>
</body>

Once you have the <textarea> on the page, you can set up the Rich Text Editor widget by calling new on the Editor widget, passing in some basic configuration options, and telling the Editor to render itself.

var myEditor = new YAHOO.widget.Editor('msgpost', {
   height: '300px',
   width: '522px',
   dompath: true,    //Turns on the bar at the bottom
   animate: true     //Animates the opening, closing and moving of
                     //Editor windows
});
myEditor.render();

7. Calendar Widget

The Calendar widget was the first thing that I used from YUI. I have used several different calendar widgets over the years, including creating my own. The YUI Calendar widget is easy to configure, use, and skin; this makes it an attractive calendar solution for web developers.

The prerequisites for this widget are minimal and include the Yahoo DOM Event and Calendar classes. I also use the base CSS stylesheet and alter it as needed. To create a calendar widget, you'll start off with the following code in the header of the HTML page.

<link rel="stylesheet" type="text/css" href="../yui/build/calendar/
   assets/skins/sam/calendar.css">

<!-- Dependencies -->
<script type="text/javascript" src="../yui/build/yahoo-dom-event/
   yahoo-dom-event.js"></script>

<!-- Source file -->
<script type="text/javascript" src="../yui/build/calendar/
   calendar-min.js"></script>

Next, create a div element in the page to act as a placement container for the calendar widget. You can put this anywhere in the page markup.

<div id="cal1Container"></div>

Lastly, instantiate the calendar object and configure it using JavaScript and the YUI methods included by your prerequisites. The first argument to the Calendar is the ID for the new element Calendar will create. This element acts as a container to the Calendar's DOM structures. The second argument is the ID of the container div element you just created on the page.

var cal1;
function init() {
   cal1 = new YAHOO.widget.Calendar("cal1","cal1Container");
   cal1.render();
}

As with a lot of other YUI widgets, you also could pass in an optional argument for configuration that sets various attributes of the Calendar including selected dates, current month, minimum and maximum dates that can be selected, and the calendar's title. There are several other configuration options as well. I encourage you to read the YUI documentation to learn more because there are way too many options to cover in this article.

8. Overlay Transition Effects

Transition effects are useful to visually 'ease in' new page elements or transition existing elements. To assign transition effects, the element needs to be an Overlay object.

Transition effects are created using the Container Effect class in combination with the effect property of the YUI Overlay object. It allows configuration of transitional animation for Overlay and its subclasses, activated when the Overlay is shown or hidden. For instance, the Overlay can fade in and out, or slide in or out of the viewport.

The Container Effect class is based on the Container and Animation classes. Both of these classes are prerequisites for transitions.

The effect property accepts an object or an array of objects, each object defining two fields. The first field is the predefined name of the effect to use and the second is the duration of the animation.

YAHOO.example.container.overlay1 =
   new YAHOO.widget.Overlay("overlay1", { xy:[150,100],
   visible:false, width:"300px",
   effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25} } );

9. Animation of HTML Elements

In addition to transition effects, you can also create motion, animate scrollbars, animate color transitions, animate along a curved path, and smoothly resize elements using the animation library in YUI.

You can animate an element on a web page by first defining the element in your markup, and then creating a new animation object using the ID of the element and lastly, calling the animate function.

<div id="test"></div>

<script>
   var myAnim = new YAHOO.util.Anim('test', {
      width: { to: 400 }
      }, 1, YAHOO.util.Easing.easeOut);
   myAnim.animate();
</script>

Properties for the animation can be defined when you instantiate the animation object or by using their respective properties.

10. Overlays and the Lightbox Technique

Take a look at how to create the famed 'Lightbox' effect by using the Overlay object in YUI.

An overlay is a widget based on the Container object, which means the Container library is a prerequisite. You also need to use the Yahoo DOM Event class.

First add your prerequisites, Yahoo DOM Event, and Container.

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

You also need to add the styles needed for the lightbox. These are included in the source download for brevity. Then, you start a JavaScript block and define the functions in the YAHOO.example namespace.

In your init function, create and render the overlay widget that will contain the larger version of the image. Next, create an overlay object that is 100% in height and width of the viewport and append this div to the body of your document. This will contain your transparent background image that makes the page appear to fade behind the larger image version. Finally, add a listener event to both the 'show' link and the close button to both show and hide the overlay.

YAHOO.example = function() {
   var $D = YAHOO.util.Dom;
   var $E = YAHOO.util.Event;
   return {
      init : function() {
         overlay_img = new YAHOO.widget.Overlay("overlay_img",
           { fixedcenter:true, visible:false, width:"330px" });
         overlay_img.render();

         // Dynamically build a second, hidden overlay div to
         // contain the transparent background image

         var overlay = document.createElement('div');
         overlay.id = 'overlay';

         // Assign 100% height and width
         overlay.style.width = $D.getViewportWidth()+'px';
         overlay.style.height = $D.getViewportHeight()+'px';
         document.getElementsByTagName('body')[0].appendChild(overlay);
         overlay.style.display = 'none';

         // Assign event listeners
         $E.addListener("show", "click", YAHOO.example.lb_show, null);
         $E.addListener("close", "click", YAHOO.example.lb_hide, null);

},

Once the init() function is defined, create two additional methods to correspond to the assigned listening events. The first is lb_show() and the second is lb_hide(). These are very simple functions that alter the visibility of the two overlay elements.

   lb_show : function() {
         $D.get('overlay').style.display = 'block';
         $D.get('overlay_img').style.visibility = 'visible';
         },

      // hide both overlay elements
      lb_hide : function() {
         $D.get('overlay').style.display = 'none';
         $D.get('overlay_img').style.visibility = 'hidden';
      }
   };
}();

The last action in your JavaScript block is to call the init function when the page loads. Use the Yahoo.util.Event by its full name because the variable $E is out of scope outside of the Yahoo.example namespace.

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

In your markup, add an image with the id "show" so you can use this image to trigger the lightbox overlay when the image is clicked. Then, add the markup for the hidden div you will use to show the larger version of the image. Here, you can see the 'close button' that has an onclick event listener assigned to call lb_hide().

   <a href="#" id="show"><img src="images/IMG_0076.jpg"
      style="height: 200px; width: 150px; border: 0;" /></a>

<div id="overlay1" style="visibility:hidden">
   <div class="hd"><span>Keyhole</span><a href="#" id="close"
      class="container-close"></a></div>
   <div class="bd"><img src="images/IMG_0076.jpg" /></div>
   <div class="ft"><span>Some sort of comment on the photo</span></div>
</div>

Download the Source Code

Download the source code for this article here.

Conclusion

YUI has a variety of widgets that make adding interactive web features easier than ever. The documentation and examples gallery are extremely useful in implementing a feature in YUI. One of the best things about YUI is that it offers a lot of great features, simple interfaces, a light footprint on page loads, and you can use a single library for about any feature you need.

References

About the Author

Diona Kidd is an owner and developer at Knowmad Technologies, an open source web development and programming firm providing content management systems, e-commerce, and custom programming services.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date