Reputation: 9001
I'm trying to display the top 5 videos of a channel. However I'm struggling to limit it to just the five.
var playListURL = 'http://gdata.youtube.com/feeds/api/users/example/uploads?v=2&alt=json&callback=?';
var videoURL= 'http://www.youtube.com/watch?v=';
$.getJSON(playListURL, function(data) {
var list_data="";
$.each(data.feed.entry, function(i, item) {
var feedTitle = item.title.$t;
var feedURL = item.link[1].href;
var fragments = feedURL.split("/");
var videoID = fragments[fragments.length - 2];
var url = videoURL + videoID;
var thumb = "http://img.youtube.com/vi/"+ videoID +"/default.jpg";
list_data += '<a href="'+ url +'" title="'+ feedTitle +'"><div class="thumbcrop" style="background-image:url('+thumb+');background-size:cover; background-position:center;"></div></a>';
});
$(list_data).appendTo(".videoClass");
});
How can I achieve this? I have tried (unsuccessfully) clauses such as while(i<6)
and if(i<6)
but neither of them display any results at all.
Upvotes: 2
Views: 6998
Reputation: 997
If you don't want to get all the results, don't use each, which does iterate through all the results in the first place. Simple as that. For limited and known number of steps use simple logic as:
for (var i = 0; i <= 4; i++) {
var item = data.feed.entry[i];
// your other stuff goes here
}
...or, as other state correctly, ommit your query by 5 in the first place and then use each
freely.
Upvotes: 3
Reputation: 8221
In the url that you are requesting your results you can add an extra parameters &max-results=5
so you can restrict the number of your feeds.
so you will have
var playListURL = 'http://.../uploads?v=2&alt=json&max-results=5&callback=?';
More on youtube data api parameters
Upvotes: 4