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 to 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.7.0/build/carousel/assets/skins/sam/carousel.css"
2<script src="http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo-dom-event.js"></script> 
3<script src="http://yui.yahooapis.com/2.7.0/build/element/element-min.js"></script> 
4<script src="http://yui.yahooapis.com/2.7.0/build/connection/connection-min.js"></script> 
5<script src="http://yui.yahooapis.com/2.7.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.yui-carousel-element li { 
2    height75px
3    width75px
4} 
view plain | print | ?

The YUI Carousel Control's constructor is passed with 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    numItems: 17 
6  }); 
7  YAHOO.util.Connect.asyncRequest("GET""php/getimages.php", { 
8      success: function (o) { 
9        var i, r = eval('(' + o.responseText + ')'); 
10        curpos = r.length; 
11 
12        for (i = 0; i < curpos; i++) { 
13          items.push(r[i]); 
14        } 
15 
16        // check if the Carousel widget is available 
17        if (typeof carousel != "undefined") { 
18          for (i = 0; i < curpos; i++) { 
19            // if so, shove the elements into it 
20            carousel.addItem(getImageTag(items[i])); 
21          } 
22          carousel.set("selectedItem", 0); 
23          items = []; 
24        } 
25      }, 
26 
27      failure: function (o) { 
28        alert("Ajax request failed!"); 
29      } 
30  }); 
31}); 
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 getImage() 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 getImage(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.

YUI Logger Output:

Logger Console

INFO 0ms (+0) 5:53:58 AM:

global

Logger initialized

Note: You are viewing this example in debug mode with logging enabled. This can significantly slow performance.

Reload with logging
and debugging disabled.

More Carousel Control Resources:

Copyright © 2009 Yahoo! Inc. All rights reserved.

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