YUI recommends YUI 3.

YUI 2 has been deprecated since 2011. This site acts as an archive for files and documentation.

YUI Library Home

YUI Library Examples: Carousel Control: Using Ajax for deferred loading of items

Carousel Control: Using Ajax for deferred loading of items

This example showcases the dynamic loading capabilities of the YUI Carousel Control. The YUI Carousel Control exposes an event called loadItems. This event is fired whenever the Carousel needs items to be loaded into it for display. Subscribing to this event makes it easy to dynamically load the next set of images.

Making the Carousel Widget dynamically load images on the fly

Here we will use the YUI Carousel Control's loadItems event to dynamically load the images on the fly.

This example has the following dependencies:

1<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.9.0/build/carousel/assets/skins/sam/carousel.css"
2<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-dom-event.js"></script> 
3<script src="http://yui.yahooapis.com/2.9.0/build/element/element-min.js"></script> 
4<script src="http://yui.yahooapis.com/2.9.0/build/connection/connection-min.js"></script> 
5<script src="http://yui.yahooapis.com/2.9.0/build/carousel/carousel-min.js"></script> 
view plain | print | ?

Initially we use YUI Connection Manager to load the initial set of items as soon as part of the DOM is visible.

1<div id="container"
2  <ol id="carousel"></ol> 
3</div> 
4<!-- The spotlight container --> 
5<div id="spotlight"></div> 
view plain | print | ?

We have a few simple CSS rules to set the dimensions for the Carousel items.

1/* Always be sure to give your carousel items a width and a height */ 
2.yui-carousel-element li { 
3    height75px
4    width75px
5} 
view plain | print | ?

The YUI Carousel Control's constructor is passed numItems (the total number of items) so that it triggers the loadItems event if the items are not available. We'll use Connection Manager to load a set of items into the Carousel as early as possible.

1YAHOO.util.Event.onDOMReady(function (ev) { 
2  var carousel, spotlight = YAHOO.util.Dom.get("spotlight"); 
3 
4  carousel = new YAHOO.widget.Carousel("container", { 
5       
6  /* Setting numItems is required for dynamic loading. This property lets Carousel 
7     know how many total items it will ever be populated with (statically and/or dynamically).
8     Not to be confused with numVisible: the number of items to display
9     per page. In this example, we don't specify numVisible and Carousel 
10     defaults to 3 items visible per page. */ 
11      
12     numItems: 17 
13  }); 
14  YAHOO.util.Connect.asyncRequest("GET""php/getimages.php", { 
15      success: function (o) { 
16        var i, r = eval('(' + o.responseText + ')'); 
17        curpos = r.length; 
18 
19        for (i = 0; i < curpos; i++) { 
20          items.push(r[i]); 
21        } 
22 
23        // check if the Carousel widget is available 
24        if (typeof carousel != "undefined") { 
25          for (i = 0; i < curpos; i++) { 
26            // if so, shove the elements into it 
27            carousel.addItem(getImageTag(items[i])); 
28          } 
29          carousel.set("selectedItem", 0); 
30          items = []; 
31        } 
32      }, 
33 
34      failure: function (o) { 
35        alert("Ajax request failed!"); 
36      } 
37  }); 
38}); 
view plain | print | ?

The YUI Carousel Control exposes a loadItems custom event that is fired when the Carousel needs more items to be loaded. This becomes very handy for us since we can subscribe to it and add more items in to the Carousel widget when required.

In our case, the server program returns an array (JSON) of images. This is parsed in the Ajax callback and then the Carousel's addItem() is called for every image. Apart from subscribing to this event, for displaying the selected image as a spotlight, we can subscribe to the itemSelected event that Carousel control exposes. This event is triggered whenever an item is selected and it returns the index of the selected item. With the index of the item, we can use the Carousel's getElementForItem() API to get the reference to the Carousel's item (an li element in our case).

1carousel.on("loadItems"function (o) { 
2  // more items available? 
3  getImages.call(this); 
4}); 
5 
6carousel.on("itemSelected"function (index) { 
7  var item = carousel.getElementForItem(index); 
8 
9  if (item) { 
10    spotlight.innerHTML = "<img src=\"" + getImage(item) + "\">"
11  } 
12}); 
13 
14carousel.render(); 
15carousel.show(); 
16 
17function getImageTag(img) { 
18    return "<img src=\"" + img + "\" height=\"75\" width=\"75\">"
19
20 
21function getImages() { 
22    var carousel = this
23                 
24    YAHOO.util.Connect.asyncRequest("GET"
25                    "assets/php/getimages.php?pos="+curpos, { 
26            success: function (o) { 
27            var i = curpos, 
28            j = 0, 
29            r = eval('(' + o.responseText + ')'); 
30         
31        curpos += r.length; 
32         
33        while (i < curpos) { 
34            if (r[j]) { 
35            carousel.addItem(getImageTag(r[j])); 
36            } else { 
37            break
38            } 
39            i++; 
40            j++; 
41        } 
42         
43        carousel.set("selectedItem", carousel.get("firstVisible")); 
44        }, 
45                         
46        failure: function (o) { 
47            alert("Ajax request failed!"); 
48        } 
49    }); 
50
view plain | print | ?

The getLargeImage() function is quite easy to implement. Since we have the reference to the Carousel's item, it is straightforward to implement a function that extracts the image within it.

1// Get the image link from within its (parent) container. 
2function getLargeImage(parent) { 
3  var el = parent.firstChild; 
4   
5  while (el) {  // walk through till as long as there's an element 
6    if (el.nodeName.toUpperCase() == "IMG") { // found an image 
7      // flickr uses "_s" suffix for small, and "_m" for big images respectively 
8      return el.src.replace(/_s\.jpg$/, "_m.jpg"); 
9    } 
10    el = el.nextSibling; 
11  } 
12   
13  return ""
14
view plain | print | ?

Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

Copyright © 2011 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings