A Look at the New YUI Carousel Control

The Yahoo! User Interface library continues to grow and expand with new components being added and existing components being continually patched and updated to ensure full x-browser support and cutting-edge functionality. Version 3 of the YUI is due for full release at some point this year, but version 2 (current release 2.6) is at this point still the stable and recommended release for general use.

One of the components recently added is the Carousel component, a control for automatically scrolling content in an attractive and intuitive interface. It’s still a beta release at present ,which indicates that the API is not finalized and that there are likely to be bugs that need addressing. We can still use the component, though, and although we should be wary as the existing API may change, the full release will probably bring more new functionality than changes in how it is implemented. 

In this tutorial we’ll be looking at a basic implementation of the control, the functionality we can use at this point in time, and the properties and methods exposed by the current API. I should point out that the examples used in this article have been thoroughly tested in today’s most common browser, but only on the Windows platform. The examples should work on other platforms, but the control or functionality may manifest itself slightly differently. You can examine the source files separately at the link, as well as check out a separate image file.

Getting Started

Let’s have a look at the default control first, and by this I mean the most basic, least configured implementation possible, the barest minimum we can code and still derive a usable widget from. In your text editor of choice create the following page: 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.6.0/build/carousel/assets/skins/sam/carousel.css">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>YUI Carousel Example 1</title>

</head>

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

<div id="scientists">

<ol>

<li><img src="img/scientists/bohr_thumb.jpg" alt="Niels Bohr"></li>

<li><img src="img/scientists/darwin_thumb.jpg" alt="Charles Darwin"></li>

<li><img src="img/scientists/einstein_thumb.jpg" alt="Albert Einstein"></li>

<li><img src="img/scientists/galileo_thumb.jpg" alt="Galileo Galilei"></li>

<li><img src="img/scientists/newton_thumb.jpg" alt="Isaac Newton"></li>

<li><img src="img/scientists/maxwell_thumb.jpg" alt="James Clerk Maxwell"></li>

</ol>

</div>

<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>

<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/element/element-beta-min.js"></script>

<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/carousel/carousel-beta-min.js"></script>

<script type="text/javascript">

 

//create carousel control

var carousel = new YAHOO.widget.Carousel("scientists");

 

//render to page

carousel.render();

 

//display

carousel.show();

 

</script>

</body>

</html>

Save this file as carousel1.html . Let’s review what we’ve got; in the <head> we link to the skin file for the carousel component provided by Yahoo. This gives the carousel its default appearance and styles the elements that get added to the page automatically. 

On the page we have a container element that holds a simple ordered list with six list items. Each item contains an image. The images used in this example are all included in the download (the images file) for this article; use them, or use images of your own, it shouldn’t make a difference. If you want to use your own images, make sure they are all of the same dimensions. 

At the end of the document (just before the closing </body> tag) we link to the script resources required by this component and then provide our own custom <script> element, which is used to create the carousel. 

First we call the constructor method, which invokes the control. The constructor takes a single argument, which is a string matching the id of the carousel’s container element. We then render the control using its render method, which creates it but doesn’t show it. Finally we call the show method, which does actually show it. When you run this file in your browser, you should see something like this:

 

 

In the default implementation a number of elements are created automatically by the widget, including the UI at the top for navigating between pages. Here we have a visual indicator of which page is selected, and also two arrows for navigating the pages. Both the page highlighter and buttons can be used to navigate the carousel pages. All of this behavior is built in and automatic, and everything should be fully functional. 

{mospagebreak title=Enhancing the Page}

We use no additional CSS of our own in the first example, and while we can happily scroll through the pages containing the images, and select individual images, nothing else really happens. Let’s add some additional elements to our page as well as some basic styling. Change carousel1.html so that it appears as follows: 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.6.0/build/carousel/assets/skins/sam/carousel.css">

<link rel="stylesheet" type="text/css" href="myCarousel.css">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>YUI Carousel Example 2</title>

</head>

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

<div id="scientists">

<span id="title">Great Men of Science</span>

<ol>

<li><img src="img/scientists/bohr_thumb.jpg" alt="Niels Bohr"></li>

<li><img src="img/scientists/darwin_thumb.jpg" alt="Charles Darwin"></li>

<li><img src="img/scientists/einstein_thumb.jpg" alt="Albert Einstein"></li>

<li><img src="img/scientists/galileo_thumb.jpg" alt="Galileo Galilei"></li>

<li><img src="img/scientists/newton_thumb.jpg" alt="Isaac Newton"></li>

<li><img src="img/scientists/maxwell_thumb.jpg" alt="James Clerk Maxwell"></li>

</ol>

</div>

<div id="information"></div>

<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>

<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/element/element-beta-min.js"></script>

<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/carousel/carousel-beta-min.js"></script>

<script type="text/javascript">

 

//create carousel control

var carousel = new YAHOO.widget.Carousel("scientists");

 

//render to page

carousel.render();

 

//display

carousel.show();

 

</script>

</body>

</html>

Save the changes as carousel2.html . We haven’t added much; a <span> element to use as the title of the carousel, and a new <div> element which will hold information about each image. We also need some CSS; in a new page in your text editor add the following stylesheet: 

#scientists { margin:0 auto; }

#title {

font-weight:bold; font-size:18px; position:absolute;

top:8px; left:10px;

}

.yui-carousel .yui-carousel-item-selected, .yui-carousel-element li {

margin:0; width:115px; height:160px;

}

#information {

width:341px; margin:0 auto; border:1px solid #808080; padding:5px;

}

#information h2 { margin:0 0 10px 0; }

#information p { margin:0; }

Save this as myCarousel.css in the same location as the HTML files. There’s really nothing worth going into much detail about in this file, except for the third rule; we need to override some of the styling provided by the component, just to tidy up the images a little. As our stylesheet comes after the carousel stylesheet, our style rules will take precedence provided we match or exceed the original specificity. 

If you view the new page in your browser, you should see the title at the top of the widget, and you may be able to tell that the images sit a little better in the carousel. 

{mospagebreak title=Additional Configuration}

The carousel currently has few configurable properties due to its beta status, but don’t worry, this is sure to change as the component grows. Let’s put some of the available properties to use in this next stage in the example; change the carousel constructor method in our final <script> element in carousel2.html so that it appears as follows (new code is shown in bold): 

var carousel = new YAHOO.widget.Carousel("scientists", {

animation: { speed: 0.5 },

isCircular: true

});

We also need to link to another library resource for this example, the animation utility, to add animation to the carousel; add the following <script> element directly before the carousel’s source file: 

<script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/animation/animation-min.js"></script>

Save the changes as carousel3.html . We used two properties in this example, the animation and isCircular properties. The animation property, which takes a literal object containing the animation parameters, enables the smooth animation of page changes in the carousel. Click on one of the buttons to see the animation in action. 

The second property enables circular behavior in the control, where instead of just ending on the final page, the component switches back to the first page automatically. Again, just run the page and check it out. 

{mospagebreak title=Working with Carousel’s Custom Events}

There’s one thing left we need to do; we need to add the behavior that changes the picture information when a new image is selected. To do this, we can use one of the many built-in custom events fired by the carousel at different points during an interaction. Change the final <script> element in carousel3.html to the following: 

//create carousel control

var carousel = new YAHOO.widget.Carousel("scientists", {

animation: { speed: 0.5 },

isCircular: true

});

 

//names

var names = [

"Niels Bohr",

"Charles Darwin",

"Albert Einstein",

"Galileo Galilei",

"Isaac Newton",

"James Clerk Maxwell"

];

 

//picture info

var info = [

"Niels Henrik David Bohr...",

"Charles Robert Darwin...",

"Albert Einstein...",

"Galileo Galilei...",

"Sir Isaac Newton...",

"James Clerk Maxwell..."

];

 

//display selected image info

carousel.on("itemSelected", function(i) {

 

//get info container

var parent = YAHOO.util.Dom.get("information");

 

//remove child elements if present

(parent.hasChildNodes() != true) ? null : removeChildren();

 

function removeChildren() {

var children = YAHOO.util.Dom.getChildren("information");

 

for(prop in children) {

parent.removeChild(children[prop]);

}

}

 

//create new heading and paragraph

var heading = document.createElement("h2");

var p = document.createElement("p");

 

//get text from arrays

var headText = document.createTextNode(names[i]);

var pText = document.createTextNode(info[i]);

 

//add text to new elements

heading.appendChild(headText);

p.appendChild(pText);

 

//add new elements to page

parent.appendChild(heading);

parent.appendChild(p);

 

});

 

//render to page

carousel.render();

 

//display

carousel.show();

Save this change as carousel4.html . Let’s review what we added. First we added two new literal arrays, the first holding the names of the distinguished gentlemen in the images, the second holding information about each of them (I trimmed it down to just their names for readability; you can see the full information in the code files). 

After the arrays we add an event handler for the custom itemSelected event, which is fired every time an image is selected (this includes the initial selection when the page loads, the automatic selection when the carousel page is changed and a manual selection with the mouse). An anonymous function is passed to the event handler as the second argument, so this function will be executed every time the event is detected. 

Within the anonymous function we first get the container element that the name and information resides in using the dom utility’s get method. We then check the container element to see whether it has any child elements. This is done using JavaScript’s ternary statement. If it does contain child elements we call the removeChildren function. 

This function uses the getChildren method to return an object containing all of the child elements. We use a for…in loop to cycle through each property in the object and remove them all. This is necessary so that the container element doesn’t fill up with names and information after several selections. 

We then create new <h2> and <p> elements and textNodes to go into them. The textNodes are populated using the i argument, which is automatically passed to our anonymous function and refers to the index number (starting at 0) of the selected image. This allows us to get the correct name and matching information out of the arrays. The new elements are then inserted into the container element and the carousel’s render and show methods are called as before. 

When you run this page in the browser, you should be able to select an image in the carousel, and have the information <div> populated with information about the picture: 

 

Summary

In this article we looked at the new YUI carousel component; while it is still early in this component’s life, enough functionality is exposed by its API for us to make good use of it. We looked at some of the basic properties and methods that can be used to work with the control programmatically and saw how the widget is rendered and behaves.

[gp-comments width="770" linklove="off" ]

chat