File Under: JavaScript

Create Rich Interfaces With the YUI Library

The line between web and desktop applications is fading. Users now expect a richer experience. JavaScript can help provide interfaces and interactions that mimic the desktop. In this tutorial, I’ll introduce you to the JavaScript-based Yahoo User Interface Library. We’ll use it to convert normal HTML into more interactive controls.

Best of all, Yahoo’s library is open-source and has been released under a BSD license, so it’s free for all users.

Contents

  1. What You’ll Need
  2. Add YUI to Your Page
  3. Go ‘Round With The Carousel Control
    1. Start With an Ordered List
    2. Transform List Into a Carousel
    3. Make it Loop Infitely
  4. Get a Date With The Calendar Control
    1. Start With an Input Field
    2. Attach a Calendar
    3. Add Some Events
  5. Where to go From Here

What You’ll Need

  • Basic knowledge of HTML and CSS
  • Some experience with JavaScript

Add YUI to Your Page

Like other JavaScript frameworks and toolkits, you can download YUI so that you’ll have all the files. The examples in this tutorial will instead use special versions containing only the code you’ll need.

Yahoo also has a file configurator to determine the YUI JavaScript and CSS files you need to access.

There are a couple upsides to going the hosted route:

1. Yahoo hosts the files for you. Save your bandwidth.
2. The files are minimized and combined into a single file. That means faster load times for your users.


If you want one a single call to YUI that will work for all the examples in this tutorial, select the following in the configurator:

  • Filter: -min
  • Options: Combine Files, Allow Rollup
  • YUI CSS Packages: Fonts CSS Package
  • YUI User Interface Widgets: Calendar Control, Carousel Control

The tool produces a single JavaScript reference and one CSS reference. Add these two lines, output from the tool, to the <head> section of your HTML file:

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/combo?2.6.0/build/fonts/fonts-min.css&2.6.0/build/calendar/assets/skins/sam/calendar.css&2.6.0/build/carousel/assets/skins/sam/carousel.css">

<script type="text/javascript" src="http://yui.yahooapis.com/combo?2.6.0/build/yahoo-dom-event/yahoo-dom-event.js&2.6.0/build/calendar/calendar-min.js&2.6.0/build/element/element-beta-min.js&2.6.0/build/carousel/carousel-beta-min.js"></script>


Before we move on to using YUI, you need to do one more thing to make Yahoo’s CSS works for styling the controls we’ll be using in this tutorial. Add the appropriate class to your page, like so:

<body class="yui-skin-sam">


OK, now we’re ready!

Go ‘Round With The Carousel Control

The rotating content pane is a common sight on information-heavy pages. For example, Yahoo’s homepage has a version that cycles through the top stories of the moment. In YUI, this is called a carousel and implementing one is easy.

You can grab the code for this entire example in Webmonkey’s Code Library, saving it as an HTML file, or simply follow along with each portion below.


Start With an Ordered List

One of the nice things about YUI Library is that it makes it easy to write code that degrades gracefully. The controls all start with basic HTML used as hooks for the JavaScript. In this case, our carousel is simply an ordered list. If the YUI code is somehow unable to load, the content will still show up in list form. It will look a little funky, but that’s better than making the page explode or showing nothing at all.

Here’s the HTML to get ready for our carousel:

    <div id="carouselcontainer">

        <ol id="carousel">

            <li>

            	<div>Monkey</div>



            </li>

            <li>

				<div>Likes</div>

            </li>

            <li>



            	<div>Riding</div>

            </li>

            <li>

            	<div>The</div>

            </li>



            <li>

            	<div>Carousel</div>

            </li>

        </ol>

    </div>



The outer div is used as a hook for the entire object. Within it, I included a simple ordered list. Each list item is a Carousel panel. You can include anything within the >li< tag. Here I’m just using a div, then adding some style. Go ahead and copy this into your stylesheet or between <style> tags in your header:

	ol#carousel li div

	{

		width: 400px;

		padding: 50px 0;

		font-size: 40px;

	}



Transform List Into a Carousel

Now it’s time to apply the code used to make our ordinary ordered list into a beautiful carousel. Inside the <head> HTML tags, place these few lines of JavaScript:

<script type="text/javascript">

function init_carousel()

{

            var carousel = new YAHOO.widget.Carousel("carouselcontainer", { numVisible: 1 }); // Create the carousel object

            carousel.render(); // Let YUI set up its styles

            carousel.show();   // Finally, show the carousel

}

YAHOO.util.Event.onDOMReady(init_carousel);

</script>


There are two pieces to the above code. First, the init_carousel function that has the three lines necessary to transform the ordered list into the carousel. Then, the final line tells YUI to wait for the Document Object Model (DOM) to load in the browser before calling the init_carousel function.

Let’s see how it works. Save the file and load it in a browser and you should see something like this:

Make it Loop Infitely

Normally programmers try to avoid infinite loops, but this is a different kind of loop. Here we want to tell the carousel that when the next button is hit on the final panel, it can go back to the first panel. Even better, let’s have it move to the next panel automatically.

Each of these features is part of the Carousel control from YUI. With just a few keystrokes, we can add them to our current carousel.

Find the first line of init_carousel and replace it with this line to create the carousel object with the features we want:

            var carousel = new YAHOO.widget.Carousel("carouselcontainer", { numVisible: 1, isCircular: true, autoPlay: 2000 }); // Create the carousel object, with auto looping


This adds two more options to the call that creates our carousel:

  1. /isCircular/ tells the final panel to go to the first panel next, to make it loop.
  2. /autoPlay/ tells how many milliseconds to wait before going to the next panel. I set this one to 2000, which is two seconds.

If you load up this new version, you’ll notice that the panels do go ’round and ’round when you click. They don’t advance on their own, despite adding autoPlay to our options. That’s because the carousel also needs us to start the autoplaying.

On the final line of init_carousel (right after the .show() line), give it the go-ahead:

            carousel.startAutoPlay();


Now your carousel should loop infinitely, all on its own!

Get a Date With The Calendar Control

The Carousel example in the previous section shows how YUI Library can help you present content in a nicer way. In this section, we’ll see an interface tool that’s even more functional. The Calendar control accepts a date from a user and adds the result into a text field, which means you get to decide the format.

You can download this entire example from Webmonkey’s Code Library or follow along with each portion below.


Start With an Input Field

Like the Carousel example, the Calendar object starts as normal HTML. In this case, we need a standard text box and an empty div, which provides the hooks necessary for YUI to build the calendar.

Add this HTML to a file that already references the JavaScript and CSS files:

<form>

    Date: <input type="text" id="datefield" />

    <div id="cal"></div>

</form>


That’s it. Now let’s write the JavaScript.


Attach a Calendar

Now we can apply the code used to make that little empty div nubbin into an interactive calendar. Inside the <head> HTML tags, place these few lines of JavaScript:

<script type="text/javascript">



function init_calendar()

{

	var cal = new YAHOO.widget.Calendar("cal", { title:"Choose a date:", close:true } );

	cal.render();

}

YAHOO.util.Event.onDOMReady(init_calendar);

</script>


Just two lines to initialize the calendar! One creates the object and the other draws it to the screen. Then one final line calls the init_calendar function when the DOM is ready.

Save and load your file and you’ll see something like this:

You may notice that two promised pieces of the calendar are so far missing:

  1. The calendar should only appear when the user clicks in the date field
  2. The calendar should add the date when the user selects one

Adding events will help us add these two features.

Add Some Events

Our calendar looks good, but it sure acts weird. In this section we’ll add two events to make the calendar behave normally.

Add these lines inside the init_calendar function:

	cal.hide();



	// Show Calendar when text field gets focus

	YAHOO.util.Event.addListener("datefield", "focus", cal.show, cal, true);



	// Save calendar value inside text field

	cal.selectEvent.subscribe(addDateText, cal, true);


There are only three lines here, though it looks like more because of empty lines and those that are commented out (the ones that start with //).

The first line hides the calendar when it loads. We don’t want to show it until the user clicks.

The second line creates a new event. Whenever the text box (with id=”datefield”) receives “focus,” the cal.show function will be called. That one line is enough to make the calendar appear whenever the user clicks into the date field.

The third line creates yet another event. It’s a special, calendar-specific event for when the user selects a date. It calls the addDateText function, which we need to create. Go ahead and add the following code above the init_calendar function:

function addDateText(type, args, obj)

{

  var datedata = args[0][0];

  var year = datedata[0];

  var month = datedata[1];

  var day = datedata[2];



  document.forms[0].datefield.value = month+'/'+day+'/'+year;

  obj.hide();

}

The parameters (/type/, /args/, /obj/) are decided by the Calendar control and automatically passed to our function. The /args/ variable contains our date data, which I extracted into three new variables: /year/, /month/, and /day/.

Then I create the text for the text box by concatenating them together. The format I used is MM/DD/YYYY, but you could manipulate the JavaScript to change it to whatever you want.

Finally, the last thing I do is to hide the calendar (passed as the /obj/ variable), because we don’t need the calendar displayed once the user has selected a date.

And that’s it. You’ve used YUI and a little bit of custom JavaScript to create a text field that lets a user choose a date from a calendar.

Where to go From Here

You’ve seen only a small piece of what’s possible with YUI Library. Here are some ideas to consider for your first unassisted foray into building something cool with YUI: