«

ctRotator – A Flexible Item/Image Rotator Script for jQuery

Posted on November 12, 2008
Filed Under Javascript, WordPress | 31 Comments     


Download Source Code
Demonstration
jQuery Plugin Directory

I was taking part in developing an interesting web application - the Thank You Project. During which I made an item rotator script that swaps a list of messages in and out from the message board. I find the rotator script is very useful, so I decide to share it. To get an overview of what the script can do, you can check the demonstration page first.

Setting Up the Script

Making sure you have all the source files and desired dependencies. Download and unpack them to a folder of your choice.

Required Dependencies:
jQuery 1.2+

Optional Dependencies:
jQuery Tooltip plugin

Include the following files to the header section of your page. Make correction to the paths according to the location of your source files.

<link rel='stylesheet' href='src/jquery.ctrotator.css' type='text/css' media='all' />


Building the Rotator

ctRotator is a very flexible in terms of customization. It offers several ways to build the rotator. For example, you can create the rotator from an manually created data source, a UL/OL list, an RSS feed, or a FlickR JSON feed. You can even create your own data source bridge to meet your special needs. In the following sections, I'll go over each one of them.

Build the Rotator from Manually Created Data Source

Data source is just an array of tuples in the following format:


Suppose you have above data source object, you can create the rotator by query and UL element and feed it with the data source:

<ul id="container"></ul>


showCount limits the number of items being showed, and speed control the rotation speed. Pretty self-explanatory.

Build the Rotator from an Exiting UL/OL element

Suppose you already have an UL or OL list, you can easily extra the data from it and feed it to the rotator. The source package contains a LI bridge, which can do this very task.

First, add bridge source to your page:

<link rel='stylesheet' href='src/jquery.ctrotator.css' type='text/css' media='all' />  
  


And then parse the list and feed it to the rotator:

<ul id="list">
  <li><a href="http://thecodecentral.com">Code Central</a></li>
  <li><a href="http://google.com">Google</a></li>
  ... so on
</ul>


ctRotatorBridgeLi takes a jQuery object as parameter. Calling getDataSource() will return a formatted data source which can be consumed by the rotator.

Build the Rotator from a RSS feed

You can create a rotating list from a RSS feed. There a a few things you need to take into consideration for RSS. The first one is one network delay of reading the feed. Because of the delay, we have to make the creation process to be asynchronous (also the reason why we used a callback function here). The second one is security model of the browsers make it impossible to fetch data from another website without using a proxy. Thus I used a proxy in examples (take a look feedproxy.php from the source package).

Include the feed bridge code to your page:

<link rel='stylesheet' href='src/jquery.ctrotator.css' type='text/css' media='all' />  
  


Create a rotator and put our rotator in a callback function:

var bridge = new ctRotatorBridgeRss20('http://thecodecentral.com/feed', function(dataSource){
    $('#container').ctRotator(dataSource, {showCount:10});
});

bridge.getDataSource();

Nothing fancy here. ctRotatorBridgeRss20 takes two parameters: a feed URL and a callback function.

We first create and bridge object, and call getDataSource() on the bridge, and the bridge extract data from RSS feed. Once the extraction is done, the callback function is called, and the extracted data is passed as function parameter (dataSource in this case). We then create the rotator and feed it with the data source.

Build the Rotator from a Flickr JSON Feed

You can also create a rotating list from a Flickr feed. We are facing the similar problem to RSS feed, which is network delay, so asynchronous handling is required. However with JSONP (JSON with Padding), we can skip creating an proxy.

Include the following bridge code to your page:

<link rel='stylesheet' href='src/jquery.ctrotator.css' type='text/css' media='all' />  
  


var bridge = new ctRotatorBridgeFlickR('http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=?', function(dataSource){
  $('#container').ctRotator(dataSource, {
    showCount:10,
    speed: 1000,
    itemRenderer:function(item){
	return '<li class="ctrotator-item"><a href="' + 
            item.url+ '"><img src="' + item.image + 
            '" alt="' + item.title + '"/></a></li>';
    }	  
  });
});

bridge.getDataSource();

What we did above were:
1. create a bridge object which can process Flickr feed and make an usable data source for the rotator.
2. Pass the data source to the callback function.
3. Inside the callback function, we create our rotator object and feed it with the data soruce.

Notice that the itemRender parameter in above code. This is my attempt to make the rotator as flexible as possible. itemRender is a callback function, which returns the HTML code that used to render the rotator row. Since Flickr feed contains image, I made some minor modification to the default renderer (have a look the default renderer in the source code). The callback function has an item parameter, which is a tuple in the data source.

As you can see, this is very flexible. For example, if you don't like to use LI to wrap items in the list, you can change LI to DIV in the renderer. You can even define your own data source format, all you have to do is to update the renderer accordingly so the rotator can be rendered properly.

itemRenderer Examples

Render items in the list as DIV element:

$('#container').ctRotator(dataSource, {
    itemRenderer: function(item){ 
    return '<div class="rotator-item">' + 
             '<a href="' + item.url + '">' + item.title + '</a>' + item.image +
             '</div>';
  }
});

Mix with different options you can create some very interesting rotator. For example, changing showCount to 1, the script becomes an ad rotator. There are also a few more options you can play with. All possible options are documented in the next section.

Integration with jQuery Tooltip Plugin

jQuery Tooltip Plugin provides a very elegant way to display extra information when space is limited.

You can easily integrate jQuery Tooltip with ctRotator. First you need to include all the required files to your page:

<link rel='stylesheet' href='src/jquery.ctrotator.css' type='text/css' media='all' />
<link rel='stylesheet' href='lib/jquery.tooltip.css' type='text/css' media='all' />




After that, set useTooltip option to true:

$('#container').ctRotator(dataSource, {
    useTooltip: true,
    tooltipOptions: {delay:500}
});

Tooltip uses "tip" field of the data source, so make sure that your data source have the "tip" field before feeding it to the rotator:

{title: 'tooltip test', url: 'http://thecodecentral.com', tip: 'tooltip description'},

Options Reference

Example: $('#container').ctRotator(dataSource, options};
Note: container typically is an UL element.

NameDefault ValueDescription
showCount5Number of items to show at any given time
speed6000duration of the swapping in milliseconds
fadeInSpeed750Item fade in speed in milliseconds
fadeOutSpeed250Item fade out speed in milliseconds
fadeEffecttrueSet to true will active fade effect
shufflefalseIf set to true, items will be displayed randomly
useTooltipfalseIf set to true, the script will show a tooltip when mouse is hovered an item
itemRendererPlease refer to the source codeControl how list item is rendered
tooltipOptionsN/AYou can use basically any options available for jQuery Tooltip: http://jquery.bassistance.de/tooltip/demo/
If you find this post useful, consider donating a few bucks to help the server running cost.

Go to Top

Subscribe to keep track of your comment.
31 Comments so far
  1. Todd December 5, 2008 10:45 am
    This is awesome... thank you very much.

    One question, how do I specify the actual url that I want (trying to pull in my own flickr photos only)??

    Thanks!
  2. Cuong December 6, 2008 11:21 am
    You need to locate the RSS/Atom feed. If you are using Firefox, you'll see a RSS icon on the right side of the address bar.

    Go to the Feed URL, change the format to JSON. For example:

    http://api.flickr.com/services/feeds/photoset.gne?set=46241&nsid=93566774@N00&lang=en-us&format=rss_200

    to

    http://api.flickr.com/services/feeds/photoset.gne?set=46241&nsid=93566774@N00&lang=en-us&format=json

    Or you can just use the RSS bridge (ctRotatorBridgeRss20 ) to pull the photos directly.
  3. WebPain December 17, 2008 12:10 pm
    Hi, I suppose in example "Build the Rotator from a RSS feed" you mean instead of ait? :-)
  4. WebPain December 17, 2008 12:21 pm
    Damn forgot the pre

    again:


    src='src/jquery.ctrotator.bridge.rss20.js'

    instead of

    src='src/jquery.ctrotator.bridge.li.js'

  5. Todd December 18, 2008 12:41 pm
    OK, cool... go the images coming in from Flickr, but how do I tell it to grab the medium size photos instead of the thumbnails?

    Thanks again for all your help!
  6. SEO December 21, 2008 7:56 am
    ??????? ??? ????????? ?? DRUGREVENUE ? ???????? ?????? ? 3000 ????????, ???????
  7. Jon December 22, 2008 4:09 am
    heya sweet script! Just wondering if you have an easy way to trigger a pause when mouseover event is fired?
  8. Cuong December 22, 2008 9:19 am
    @WebPain
    Thank you for pointing this out. I updated the script path.

    @Jon
    You would have to modify the script. You can create a flag and set it true when mouse is hovered the desired element, and set it to false when mouse is out. In updateRotation function of jquery.ctrotator.js, do something like this:

    <pre>
    var mFlag.
    function updateRotation(rotator, container, options){
    if(mFlag){
    return;
    }
    var item = rotator.gotoNext();


    Haven't tested it, but hopefully it gives you a pointer.
  9. Jon December 22, 2008 10:17 am
    hi there, thanks for that it appears to pause it fine, but for whatever reason it doesnt continue with the mouse out. I will dig deeper on this one but cheers for the pointer.

    Another question if i may the RSS feed works perfectly in FireFox but i cant get it working in IE at all. (using IE 7 here) just wondering if you know of any IE quirks at all?
  10. Jon December 23, 2008 5:17 am
    just thought i would update in case others run into similar troubles:

    Pause on mouse over: i needed to add the setTimeout bit..
    if(mFlag == true){
    setTimeout(function(){updateRotation(rotator, container, options)}, options.speed);
    return;
    }

    as for the RSS not working in IE. it was a drupal issue not returning a valid content type for the feed and as such it was being ignored. updated the content type in the node.module script and it fixed the issue.
  11. Leon January 6, 2009 5:13 am
    Hi there, excellent script!

    Further to Todd's last question, what is the correct way of controlling the image size that's pulled from Flickr?

    The default seems to obtain the 'Small' size, and I'd like to retrieve something larger (if possible).

    Thanks.
  12. Kris January 15, 2009 10:27 am
    Is there an easy way to make the speed random between a certain set of parameters ie. Random speed between 3000 and 10000?

    I'm basically adding this to a recent forum posts section and am wanting it to appear like posts are being added as it reveals a new post. I just think it might be more realistic if I had them appearing at random intervals.
  13. Elle January 16, 2009 9:16 pm
    This is great. Almost what I was looking for. Just wanted to ask: is there anyway to change the speed to be on page reload instead?
  14. marco February 8, 2009 8:44 am
    Hi,

    really interesting tool.
    I would to know if it is possible to apply to a table where the lines are a Col1Col2.
  15. marco February 8, 2009 8:53 am
    tr td Col1 /td td Col2 /td /tr
  16. Sean February 18, 2009 8:55 pm
    @Jon

    Could you post the other mods required to make the mouseover pause work 'You can create a flag and set it true when mouse is hovered the desired element, and set it to false when mouse is out'

    Ta
  17. [...] cRotator, ancora mai provato (esempi) [...]
  18. Gurpreet Singh March 15, 2009 5:19 am
    Hey there!!!
    Thats really awesome work you have done there.
    Thanks a lot for that.
    I had used your code in one of the webpages that I built. I was referencing the way to add the files and the code into the webpage. But now its not there, the way it was earlier. Can you please put it back so that I can get the exact way and code to put "Build Rotator from Flickr Feed" into a webpage.

    I'll be very grateful to you, if you can put it back soon.
    Thanks in advance.
  19. damir March 19, 2009 12:18 am
    hi,
    Very cool stuff and i like it, but i have a problem , I am trying to make the same file like
    http://api.flickr.com/services/feeds/photos_public.gne?format=json&amp;jsoncallback=?
    on my server with .php and it's writing out the result
    and when i put it here
    new ctRotatorBridgeFlickr('http://www.myurl.com/script.php', function(dataSource){
    the script is not working,I have checked all links and they are correct. If someone have any idea how to make it work ?
    Please help
    Best regards
  20. damir March 24, 2009 6:17 am
    hey .
    how can i make it to start rotating when the mouse is on the image, and to stop rotating when is off the image?
    thanks in advance
  21. Samuel Pickard April 7, 2009 8:10 am
    Hey,

    I've written a Twitter bridge for this as well, so you can rotate tweets from an RSS search from search.twitter.com.

    I also need it to refresh the data periodically, not just keep rotating the same items. Is there anyway to do this?

    Thanks


    function ctRotatorBridgeTwitter(url, readyCallback) {

    this.url = url;
    this.readyCallback = readyCallback;
    }

    ctRotatorBridgeTwitter.prototype =
    {
    getDataSource: function()
    {
    var readyCallback = this.readyCallback;
    var dataSource = [];
    $.get(this.url, {}, function(data)
    {
    $(data).find('channel item').each(function()
    {
    var e = $(this);
    dataSource.push(
    {
    title: e.find('title').text(),
    url: e.find('link').text(),
    image: e.find('google\\:image_link').eq(0).text()
    });
    });
    readyCallback(dataSource);
    }, 'xml');

    return dataSource;
    }

    };

  22. Maxim May 5, 2009 5:08 am
    Hello

    How can I stop rotating?
  23. I’ll try applying these scripts. Thanks.
  24. Tom August 2, 2009 6:55 pm
    You can stop rotating simply by altering the script and looking at about line 50. You're looking for the call to updateRotation. You'll want to put in a simple condition. I basically said if it's 0, don't rotate. Why would we want to rotate in rapid fire anyway? Perhaps this could be included in the next release?

    if(options.speed &gt; 0) {

    updateRotation(rotator, container, options);
    }

    Why? Well because it's quite handy to not have it rotate...and then in the callback function where it displays the list of photos, count the length of the json object (feed from datasource)...So say we do:

    var totalImages = dataSource.length;

    Now in the options object we specify to the rotator we can say:

    $('#flickr').ctRotator(dataSource, {
    showCount: totalImages,
    speed: 0,
    ...

    That will then show all the images in the feed and not rotate them.
    With a little creativity we can change the output in the itemRenderer and return some id's in those anchor links. Then take jQuery and handle events for clicking those and instead of going to the image make it bring up a lightbox or appear in another area on the page, etc.

    This very quickly turns the rotator plugin here into a very customizable gallery plugin as well.

    I like how it's a very minimal script -- many other scripts I've seen for galleries are way too bloated. This is much better. It also leaves things client side. "Mash-up" away for little hit to your server.

    My only request (and I haven't looked at the script long enough to figure it out) is that there was an event listener to updateRotation()... So I can have a "next" and ultimately "prev" link to move the list. That would mean the rotation needs to go in reverse too, which would be more alteration...but specified in the options again by perhaps "direction: forward" or "direction: reverse".

    That would be really nice. Then it's essentially exactly the same, but completely flexible to serve as originally intended, but also as a much more complex gallery (with some elbow grease).

    Thanks for writing this script!
  25. Seven August 28, 2009 12:29 pm
    This is a great script and just what I needed for a WordPress template I am working on.

    I have another project however wherein I am having an issue using images in an existing . Any suggestions?
  26. ctRotator | jQuery Wisdom November 13, 2009 10:36 pm
    [...] HTML UL/OL list, RSS feed, Flickr feed. More data sources can be supported with custom bridges. Web Site Demo Download Share and [...]
  27. mike khattab December 2, 2009 3:18 am
    When using jQuery 1.2.6, things are fine, but not with JQuery 1.3.2 where the rotator causes screen disturbance or flickering of the footer at the bottom of the page. This happens only when the page is scrolled to the bottom completely, and both the footer and rotator are visible.

    I would be thankful for a solution or an update
  28. Luiz January 11, 2010 5:18 am
    I have a list with some images:

    &lt;ul id=&quot;listaEmpresasConveniadas&quot;&gt;
    &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;img src=&quot;imagens/___empresa1.gif&quot; width=&quot;81&quot; height=&quot;46&quot; /&gt;teste&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;img src=&quot;imagens/___empresa2.gif&quot; width=&quot;81&quot; height=&quot;47&quot; /&gt;Teste&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#&quot;&gt;&lt;img src=&quot;imagens/___empresa3.gif&quot; width=&quot;84&quot; height=&quot;44&quot; /&gt;Teste&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;

    These images is not displayed, just de text.

    Is there some way to fix it?
  29. Luiz January 12, 2010 8:52 am
    Hi again,

    I tried to use the "itemRenderer" parameter, but I didn't have success.

    The item.url, item.title works well, but the item.image is always undefined.

    My source code:


    $(document).ready(function(){
    var dataSource = new ctRotatorBridgeLi($('#areaAuxiliar #listaEmpresasConveniadas ul')).getDataSource();

    $('#areaAuxiliar #listaEmpresasConveniadas ul').ctRotator(dataSource, {
    showCount: 3,
    speed: 1000,
    itemRenderer: function(item){
    return '<a href="' + item.url + '" rel="nofollow"></a>' + item.title + ' - ' + item.image + '';
    }
    });
    });

    &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;/Teste/&quot;&gt;&lt;img src=&quot;imagens/___empresa1.gif&quot; width=&quot;81&quot; height=&quot;46&quot; /&gt;Empresa 1&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;/Teste/&quot;&gt;&lt;img src=&quot;imagens/___empresa2.gif&quot; width=&quot;81&quot; height=&quot;47&quot; /&gt;Empresa 2&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;/Teste/&quot;&gt;&lt;img src=&quot;imagens/___empresa3.gif&quot; width=&quot;84&quot; height=&quot;44&quot; /&gt;Empresa 3&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;


    I need help, please.
  30. Andrew Philpott January 19, 2010 8:15 am
    Is there a way to use this with sifr? I tried adding a callback function and the rotator is working, but not the font replacement.
  31. Marcos Vinicius January 23, 2010 9:23 am
    I would like to know how can I call php data sources, recordsets in dreamweaver using this script.
Code Central Special

Polls

  • Your opinion about the design of this site:

    View Results

    Loading ... Loading ...