In this post I'm going to show you a simple implementation (yet to be a little bit enhanced) of a Flickr cross-fade image rotator with jQuery. The script itself is made up of two components: a call to the
$.getJSON() method to fetch the JSONP Flickr feed and a JavaScript timer to rotate the retrieved images. First of all, let's define our CSS styles to display our rotator:
#flickr-slider {
width: 400px;
margin: 0 auto;
text-align: center;
}
#flickr-slider img {
display: none;
}
Since we'll use an AJAX method, we must define our timer within the getJSON() scope or it won't work:
$(function() {
var flickrBaseURL = 'http://api.flickr.com/services/feeds/photos_public.gne?tags=tree&format=json&jsoncallback=?';
$.getJSON(flickrBaseURL, function(data){
$.each(data.items, function(i, item){
$('<img/>').attr('src', item.media.m).appendTo('#flickr-slider');
return i < 10;
});
var imgLength = 11;
var index = -1;
var $img = $('img', '#flickr-slider');
var interval = window.setInterval(function() {
index++;
if(index == imgLength) {
index = -1;
}
$img.eq(index).
fadeIn(2000).
siblings().
hide();
}, 2000);
});
});
We set an index and a limit. When the index reaches its limit, we reset it to -1 so that the eq() method can start again from the very first image. You can see the demo below.