Possiamo anche utilizzare le API JSON o JSONP di YouTube, Vimeo, Flickr ed altri web service per creare le slide del nostro slideshow.
Dato che la risposta del server remoto può non essere immediata, dobbiamo creare un indicatore di caricamento per indicare che il download delle risorse è in corso.
<div class="slider" id="main-slider"><!-- contenitore esterno -->
<div class="slider-wrapper"><!-- contenitore interno -->
</div>
<div class="slider-nav"><!-- "Precedente" e "Successivo" -->
<button class="slider-previous">Precedente</button>
<button class="slider-next">Successivo</button>
</div>
<div id="spinner"></div><!-- indicatore di caricamento -->
</div>
I passi da seguire sono:
- Reperire i dati remoti
- Nascondere l'indicatore di caricamento
- Effettuare il parsing dei dati
- Costruire il contenuto HTML
- Creare le slide
- Gestire lo slideshow.
Possiamo ad esempio reperire i video di un utente da YouTube. In jQuery il codice è il seguente:
(function( $ ) {
$.fn.slideshow = function( options ) {
options = $.extend({
wrapper: ".slider-wrapper",
//...
loader: "#spinner",
//...
limit: 5,
username: "gabrieleromanato"
}, options);
//...
var getVideos = function() {
// Prende i video da YouTube
var ytURL = "https://gdata.youtube.com/feeds/api/videos?alt=json&author=" + options.username + "&max-results=" + options.limit;
$.getJSON( ytURL, function( videos ) { // Oggetto JSON
$( options.loader ).hide(); // Nasconde l'indicatore di caricamento
var entries = videos.feed.entry;
var html = "";
for( var i = 0; i < entries.length; ++i ) { // Parsing e creazione della stringa HTML
var entry = entries[i];
var idURL = entry.id.$t;
var idVideo = idURL.replace( "http://gdata.youtube.com/feeds/api/videos/", "" );
var ytEmbedURL = "https://www.youtube.com/embed/" + idVideo + "?rel=0&showinfo=0&controls=0";
html += "<div class='slide'>";
html += "<iframe src='" + ytEmbedURL + "' frameborder='0' allowfullscreen></iframe>";
html += "</div>";
}
$( options.wrapper ).html( html ); // Creazione delle slide
});
};
return this.each(function() {
//...
getVideos();
// Gestione dello slideshow
});
};
})( jQuery );